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)
Popularity: 36% [?]
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
It worked for me too. Thank you very much – I couldn't understand this.
Hi,
How to detect two white space in text altogether so that we can remove it in C#
Thanks very much.
I want something like this:
If below is my string
ROBERT EATS MEAT.
Write a C# Code to Extract the first Letter, and add it to the last word. e.g i want to return
RMEAT.
How do i do that?
thanks in advance
I think a better approach is to use the Split function and throw away the blank tokens. Then you can re-concatenate the tokens with or without a single space in between (as in, normal sentence spacing).
Thanks so much. I've been trying to clean MAC addresses so that it doesn't matter if you hand it "0011223344″, or "00:11:22:33:44″, or "00 11 22 33 44″.
My button_click code…
string macString = textBox1.Text.Replace( ":", "" );
macString = macString.Replace("-", "");
macString = macString.Replace(" ", "");
WakeFunction(macString);