You probably knew that you can use the String.Trim method to remove whitespace from the start and end of a C# string.  Unfortunately, the Trim method does not remove whitespace from the middle of a string.

Given this example:

string text = "  My testnstringrn ist quite long  ";
string trim = text.Trim();

The ‘trim’ string will be:

“My testnstringrn ist quite long”  (31 characters)

Another approach is to use the String.Replace method, but that requires you to remove each individual whitespace character via multiple method calls:

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

The best approach is to use 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 whitespace character including the space, tab, linefeed and newline.

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

The ‘trim’ string will be:

“Myteststringisquitelong”  (23 characters)

Share and Enjoy:
  • Digg
  • Twitter
  • Facebook
  • Reddit
  • StumbleUpon
  • LinkedIn
  • Google Bookmarks
  • Slashdot