C# | Insert() Method
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:
// C# program to demonstrate the// Insert methodusingSystem;classGeeks {// Main MethodpublicstaticvoidMain(){// stringString str ="GeeksForGeeks";Console.WriteLine("Current string: "+ str);// insert GFG at index 5 where string is appendConsole.WriteLine("New string: "+ str.Insert(5,"GFG"));}}Output:Current string: GeeksForGeeks New string: GeeksGFGForGeeks
- Program 2:
// C# program to demonstrate the// Insert methodusingSystem;classGeeks {// Main MethodpublicstaticvoidMain(){// stringString str ="GeeksForGeeks";Console.WriteLine("Current string: "+ str);// insert space at index 8 where string is appendConsole.WriteLine("New string: "+ str.Insert(8," "));}}Output:Current string: GeeksForGeeks New string: GeeksFor Geeks
- Program 3:
// C# program to demonstrate the// Insert methodusingSystem;classGeeks {// Main MethodpublicstaticvoidMain(){Console.WriteLine("Hey Started".Insert(3," ProGeek2.0"));}}Output:Hey ProGeek2.0 Started
Reference: https://msdn.microsoft.com/en-us/library/system.string.insert


