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


Question

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
1
408
9/24/2012 3:19:02 AM

Accepted Answer

RegexOptions options = RegexOptions.None;
Regex regex = new Regex("[ ]{2,}", options);     
tempo = regex.Replace(tempo, " ");
420
2/3/2016 11:27:56 AM

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.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon