Inserting and Removing Substrings

You can use the String.Insert method to insert a substring into the middle of an existing string.
1
2
3
string s = "John Adams";
int n = s.IndexOf("Adams");
s = s.Insert(n, "Quincy ");    // s now "John Quincy Adams"
Remember that a string is immutable.  Invoking Insert on a string but not assigning the result to anything will have no effect on the string.
1
2
string s = "John Adams";
s.Insert(5, "Quincy ");    // Allowed, but s is not changed
You can use the String.Remove method to remove a specified number of characters from a string, starting at specified 0-based index.  (Again, you must assign the resulting string to something).


1
2
3
string s = "OHOLEne";
s = s.Remove(1, 4);      // Start at position 1, remove 4 characters
Console.WriteLine(s);    // "One"