Problem
You have a text (either a char or a string value) that needs to be inserted into a different string at a particular position.
Solution
The insert instance method of the String class makes it easy to insert a string or char into a string.
Below are the programs to illustrate the Insert() Method :
Example 1: C# Insert text in a String
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | class Program { static void Main(string[] args) { string sourceString = "Here the text is inserted =><="; sourceString = sourceString.Insert(28, "Insertion"); Console.WriteLine(sourceString); Console.ReadLine(); } } |
In the string sourceString a second string is inserted between the characters > and <. The result is:
Example 2: Insert space in string C#
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | class Program { static void Main(string[] args) { // string String str = "CodeExample"; Console.WriteLine("Current string: " + str); // insert " " at index 4 where string is append Console.WriteLine("New string: " + str.Insert(4, " ")); Console.ReadLine(); } } |
Output:
Example 3: C# add character to string at position, C# insert character into string every
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | class Program { static void Main(string[] args) { // string String str = "CodeExample"; Console.WriteLine("Current string: " + str); // insert " " at index 4 where string is append Console.WriteLine("New string: " + str.Insert(4, "4")); Console.ReadLine(); } } |
Example 4: C# add to beginning of string
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | class Program { static void Main(string[] args) { // string String str = "Example"; Console.WriteLine("Current string: " + str); // insert "Code" at beginning of string Console.WriteLine("New string: " + str.Insert(0, "Code")); Console.ReadLine(); } } |
Example 5: C# append to end of string. C# add text to end of string
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | class Program { static void Main(string[] args) { // string String str = "Code"; Console.WriteLine("Current string: " + str); // insert "Code" at beginning of string Console.WriteLine("New string: " + str.Insert(str.Length, "Example")); Console.ReadLine(); } } |
Output:
Reference:Ā https://msdn.microsoft.com/en-us/library/system.string.insert