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, you do not require the overhead of using a regular expression to aid in the replacing operation.
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
variable 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 a place-holding string within a string, use the following ...
Get C# Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.