2.7. Removing or Replacing Characters Within a String
Problem
You have some text within a string that needs to be either removed or replaced with a different character or string. Since the replacing operation is somewhat simple, using a regular expression to aid in the replacing operation is not worth the overhead.
Solution
To remove a substring from a string, use the Remove instance method on the String class. For example:
string name = "Doe, John"; name = name.Remove(3, 1); Console.WriteLine(name);
This code creates a new string and then sets the name variable to refer to it. The string contained in name now looks like this:
Doe John
If performance is critical, and particularly if the string removal operation occurs in a loop so that the operation is performed multiple times, you can instead use the Remove method of the StringBuilder object. The following code modifies the internal state of the StringBuilder object that the str variable references so that its value becomes 12345678:
StringBuilder str = new StringBuilder("1234abc5678", 12);
str.Remove(4, 3);
Console.WriteLine(str);To replace a delimiting character within a string, use the following code:
string commaDelimitedString = "100,200,300,400,500";
commaDelimitedString = commaDelimitedString.Replace(',', ':');
Console.WriteLine(commaDelimitedString);This code creates a new string and then makes the commaDelimitedString variable refer to it. The string in commaDelimitedString now looks like this:
100:200:300:400:500
To replace ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access