How do I replace multiple spaces with a single space in C#?

Pokus picture Pokus · Oct 16, 2008 · Viewed 303.8k times · Source

How can I replace multiple spaces in a string with only one space in C#?

Example:

1 2 3  4    5

would be:

1 2 3 4 5

Answer

Matt picture Matt · Oct 16, 2008

I like to use:

myString = Regex.Replace(myString, @"\s+", " ");

Since it will catch runs of any kind of whitespace (e.g. tabs, newlines, etc.) and replace them with a single space.