Matt Matt - 1 year ago 83
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?

Answer Source
string cleanedString = System.Text.RegularExpressions.Regex.Replace(dirtyString,@"\s+"," ");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download