In C#, Insert() method is a String method. It is used to return a new string in which a specified string is inserted at a specified index position in the current string instance.
Syntax:
public string Insert(int Indexvalue, string value)
Explanation:
- Indexvalue: It is the index position of current string where the new value will be inserted. The type of this parameter is System.Int32.
- value: The String value to be inserted the type of this parameter is System.String.
Exceptions:
- ArgumentNullException: If the String value is null.
- ArgumentOutOfRangeException: If Indexvalue is negative or greater than the length of the string.
Note: This method always returns a new string which is modified with value inserted at the specified position. The return value type of Insert() method is System.String. If Indexvalue is equal to the length of the current instance, then the value is appended to the end of this instance.
Example:
Input : str = "GeeksForGeeks"
str.Insert(5, "GFG");
Output: GeeksGFGForGeeks
Input : str = "GeeksForGeeks"
str.Insert(8, " ");
Output: GeeksFor Geeks
Below are the programs to illustrate the Insert() Method :
- Program 1:
using System;
class Geeks {
public static void Main()
{
String str = "GeeksForGeeks" ;
Console.WriteLine( "Current string: " + str);
Console.WriteLine( "New string: " + str.Insert(5, "GFG" ));
}
}
|
Output:
Current string: GeeksForGeeks
New string: GeeksGFGForGeeks
- Program 2:
using System;
class Geeks {
public static void Main()
{
String str = "GeeksForGeeks" ;
Console.WriteLine( "Current string: " + str);
Console.WriteLine( "New string: " + str.Insert(8, " " ));
}
}
|
Output:
Current string: GeeksForGeeks
New string: GeeksFor Geeks
- Program 3:
using System;
class Geeks {
public static void Main()
{
Console.WriteLine( "Hey Started" .Insert(3, " ProGeek2.0" ));
}
}
|
Output:
Hey ProGeek2.0 Started
Reference: https://msdn.microsoft.com/en-us/library/system.string.insert
Last Updated :
31 Jan, 2019
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...