
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Removing or Replacing Characters Within a String
|
53
2.10 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 str vari-
able 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); ...