Coder Perfect

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

Problem

In C#, how can I replace numerous spaces in a string with a single space?

Example:

1 2 3  4    5

would be:

1 2 3 4 5

Asked by Pokus

Solution #1

I prefer to utilize the following phrases:

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

Because it will catch any type of whitespace (tabs, newlines, etc.) and replace it with a single space.

Answered by Matt

Solution #2

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

Answered by Patrick Desjardins

Solution #3

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

Answered by tvanfosson

Solution #4

Matt’s response is the finest, but I don’t believe it is correct. You must use the following syntax to substitute newlines:

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

Answered by Brenda Bell

Solution #5

Another LINQ-based technique is:

 var list = str.Split(' ').Where(s => !string.IsNullOrWhiteSpace(s));
 str = string.Join(" ", list);

Answered by cuongle

Post is based on https://stackoverflow.com/questions/206717/how-do-i-replace-multiple-spaces-with-a-single-space-in-c