Advertisement
Advertisement


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


Question

How can I replace multiple spaces in a string with only one space in C#?

Example:

1 2 3  4    5

would be:

1 2 3 4 5
2012/09/24
1
455
9/24/2012 3:19:02 AM

Accepted Answer

string sentence = "This is a sentence with multiple    spaces";
RegexOptions options = RegexOptions.None;
Regex regex = new Regex("[ ]{2,}", options);     
sentence = regex.Replace(sentence, " ");
2020/03/04
487
3/4/2020 8:32:21 AM


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

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);
2010/05/20

Another approach which uses LINQ:

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

It's much simpler than all that:

while(str.Contains("  ")) str = str.Replace("  ", " ");
2012/11/08

Regex can be rather slow even with simple tasks. This creates an extension method that can be used off of any string.

    public static class StringExtension
    {
        public static String ReduceWhitespace(this String value)
        {
            var newString = new StringBuilder();
            bool previousIsWhitespace = false;
            for (int i = 0; i < value.Length; i++)
            {
                if (Char.IsWhiteSpace(value[i]))
                {
                    if (previousIsWhitespace)
                    {
                        continue;
                    }

                    previousIsWhitespace = true;
                }
                else
                {
                    previousIsWhitespace = false;
                }

                newString.Append(value[i]);
            }

            return newString.ToString();
        }
    }

It would be used as such:

string testValue = "This contains     too          much  whitespace."
testValue = testValue.ReduceWhitespace();
// testValue = "This contains too much whitespace."
2015/11/20

Source: https://stackoverflow.com/questions/206717
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]