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 test\nstring\r\n is\t quite long  ";
string trim = text.Trim();

The 'trim' string will be:

"My test\nstring\r\n is\t 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:

ASP.NET Web Hosting – 3 Months Free and Free Setup

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)

Related posts:

  1. Strings Don't Add Up
  2. C# Search/Replace in Files
  3. Clean/Strip/Remove Binary Characters from C# String
  4. Check Valid File Path in C#
  5. Convert Binary to Base64 String