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:
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:


very good
"Unfortunately, the Trim method does not remove whitespace from the middle of a string."
How is that unfortunate? a string with no whitespace at the beginning or end is FAR FAR more useful than a string with all whitespace removed.
"How is that unfortunate? a string with no whitespace at the beginning or end is FAR FAR more useful than a string with all whitespace removed."
Well, that depends on the application, doesn't it?
It's unfortunate because it would've been nice for the Trim method to handle all cases. e.g.,
[Flags]
public enum TrimOptions
{
Start = 0×01,
Middle = 0×02,
End = 0×04,
}
This is a nice and simple example
you could use
string trim = Regex.Replace(text, @"\s+", " ").Trim();
if you want to keep the words seperated with spaces
e.g.
for this example we will get :
My test string is quite long
Cheers Adam. That was helpful
Thanks…It helped