How to replace multiple white spaces with one white space

Matt picture Matt · Aug 14, 2009 · Viewed 107.6k times · Source

Let's say I have a string such as:

"Hello     how are   you           doing?"

I would like a function that turns multiple spaces into one space.

So I would get:

"Hello how are you doing?"

I know I could use regex or call

string s = "Hello     how are   you           doing?".replace("  "," ");

But I would have to call it multiple times to make sure all sequential whitespaces are replaced with only one.

Is there already a built in method for this?

Answer

Tim Hoolihan picture Tim Hoolihan · Aug 14, 2009
string cleanedString = System.Text.RegularExpressions.Regex.Replace(dirtyString,@"\s+"," ");