Given a set of characters, remove those characters from a string in C#.

It is common knowledge that string is immutable in C#, i.e., we cannot change the contents of a string object; we can change only the reference to the object. Therefore, to remove any characters from a string, we need to create its new instance. This post provides an overview of several methods to accomplish this:

1. Using String.Replace() method

A fairly simple solution is to use the String.Replace() method for replacing all occurrences of specified characters in the current string. This is demonstrated below:

Download  Run Code

 
We can also use the List.ForEach() method in place of the foreach loop, as shown below:

Download  Run Code

2. Using String.Split() method

The idea is to split the string with given characters. This can be easily done using the String.Split() method, as demonstrated below:

Download  Run Code

3. Regular Expressions

We can use regular expressions to remove specific characters in a string. The idea is to check for specific characters in a string and replace them with an empty string. The following code example shows how to implement this. Note below implementation will fail for characters that need escaping.

Download  Run Code

That’s all about removing specific characters from a string in C#.