insert a string into another string at a specific index in csharp

To insert a string into another string at a specific index in C#, you can use the Insert method of the StringBuilder or String class, or you can manipulate the string using the Substring method.

Here's an example using the Insert method:

main.cs
string originalString = "Hello world!";
string stringToInsert = "beautiful ";
int index = 6; // insert at index 6 (before "world!")

StringBuilder sb = new StringBuilder(originalString);
sb.Insert(index, stringToInsert);
string newString = sb.ToString();

Console.WriteLine(newString); // "Hello beautiful world!"
314 chars
10 lines

And here's an example using the Substring method:

main.cs
string originalString = "Hello world!";
string stringToInsert = "beautiful ";
int index = 6; // insert at index 6 (before "world!")

string newString = originalString.Substring(0, index) + stringToInsert + originalString.Substring(index);

Console.WriteLine(newString); // "Hello beautiful world!"
298 chars
8 lines

gistlibby LogSnag