Remove Whitespace from C# Strings

We usually use the String.Trim method to remove white space from the start and end of a C# string.  But unfortunately, the System.Trim method does not remove white space from the middle of a string.

Example would be

string text = "  Test string   for this blog  ";
string trim = text.Trim();

The trim output will be

Test string   for this blog

Hmm…, still white space in the middle.

Other way in which we can achieve this is to use the String.Replace method, but that requires us to remove each individual white space character via multiple method calls:

Again, example would be

string trim = text.Replace( " ", "" );
trim = trim.Replace( "r", "" );
trim = trim.Replace( "n", "" );
trim = trim.Replace( "t", "" );

NOTE: The ‘r’, ‘n’, ‘t’ are Escape Sequences, in case we would used it for formatting the output.

The trim output will be


Which is most likely doesn’t seems to the one we want!

The best way is use of regular expressions. You can use the Regex.Replace method, which replaces all matches defined by a regular expression with a replacement string. In this case, use the regular expression pattern “s”, which matches any white space character including the space, tab, linefeed and newline.

string trim = Regex.Replace(text, @"s+", " ").Trim();

The trim output will be:

Test string for this blog

That what we were looking for…… 🙂

You can download the cheat sheet of Regular expression regular-expressions-cheat-sheet-v2.pdf

Hope this helps.

Tagged with: , ,
  • Magnificent goods from you, man. I have have in mind your
    stuff previous to and you are just too excellent. I really like what you’ve acquired here, really like what you are stating and
    the best way in which you say it. You make it entertaining and you continue
    to care for to keep it smart. I can not wait to
    read much more from you. This is really a wonderful site.