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

前端 未结 24 1688
面向向阳花
面向向阳花 2020-11-22 06:37

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         


        
24条回答
  •  时光取名叫无心
    2020-11-22 07:06

    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."
    

提交回复
热议问题