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

string sentence = "This is a sentence with multiple    spaces";
RegexOptions options = RegexOptions.None;
Regex regex = new Regex("[ ]{2,}", options);     
sentence = regex.Replace(sentence, " ");

I think Matt's answer is the best, but I don't believe it's quite right. If you want to replace newlines, you must use:

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

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.


string xyz = "1   2   3   4   5";
xyz = string.Join( " ", xyz.Split( new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries ));

Tags:

C#

String

Regex