#103 – Inserting and Removing Substrings
September 28, 2010 Leave a comment
You can use the String.Insert method to insert a substring into the middle of an existing string.
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.
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).
string s = "OHOLEne"; s = s.Remove(1, 4); // Start at position 1, remove 4 characters Console.WriteLine(s); // "One"