Matt Matt - 8 months ago 38
C# Question

How to replace multiple white spaces with one white space

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?

string cleanedString = System.Text.RegularExpressions.Regex.Replace(dirtyString,@"\s+"," ");