Remove duplicated whitespaces on C#

The Trim method on C# only removes whitespaces at the beginning and at the end of a string, but it does not remote duplicated whitespaces inside the string (like the Trim function on VB for Apps), which is very handy sometimes.

One of the ways to do it on C#, is using Regular Expressions. This method will not only remove whitespaces but also tabs and line breaks, and will replace them with one whitespace.

string s1 = "He saw   a cute\tdog.\nThere\n\twas another sentence.";
Regex r = new Regex(@"\s+");
string s2 = r.Replace(s1, @" ");
// The result would be: He saw a cute dog. There was another sentence.

You will need to add the reference to System.Text.RegularExpressions to your namespace.
Source: Dot Net Perls

Leave a Reply

Your email address will not be published. Required fields are marked *

Are you human? *