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

前端 未结 24 1436
面向向阳花
面向向阳花 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:16

    For those, who don't like Regex, here is a method that uses the StringBuilder:

        public static string FilterWhiteSpaces(string input)
        {
            if (input == null)
                return string.Empty;
    
            StringBuilder stringBuilder = new StringBuilder(input.Length);
            for (int i = 0; i < input.Length; i++)
            {
                char c = input[i];
                if (i == 0 || c != ' ' || (c == ' ' && input[i - 1] != ' '))
                    stringBuilder.Append(c);
            }
            return stringBuilder.ToString();
        }
    

    In my tests, this method was 16 times faster on average with a very large set of small-to-medium sized strings, compared to a static compiled Regex. Compared to a non-compiled or non-static Regex, this should be even faster.

    Keep in mind, that it does not remove leading or trailing spaces, only multiple occurrences of such.

提交回复
热议问题