#103 – Inserting and Removing Substrings

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"

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: