This article illustrates the different techniques to strip punctuations from a string in C#.

1. Using Char.IsPunctuation() method

The Char.IsPunctuation() method return true if the specified character is a punctuation mark; otherwise, false. The following code demonstrates the usage of the IsPunctuation() method with LINQ’s Where() method to strip punctuations from a string. This would require the System.Linq namespace.

Download  Run Code

 
If you are not allowed to use LINQ, try using the below code. It creates an extension method to strip punctuations from a string, that uses a foreach loop to iterate over the string and collect all non-punctuation characters in a StringBuilder instance.

Download  Run Code

2. Using Regex.Replace method

Another option is to use a regular expression to strip all punctuation characters from a string. In C#, you can use the Regex.Replace() method for this. The following solution uses the !"#$%&'()*+,-./:;<=>?@\[\]^_`{|}~, which includes all US-ASCII punctuation characters. If there are any other characters that you want to remove, you can easily add them in this regex.

Download  Run Code

 
The code can be shortened using the \p{P} character class, which matches with the US-ASCII punctuation by default.

Download  Run Code

That’s all about stripping punctuations from a string in C#.