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

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

    Here is a slight modification on Nolonar original answer.

    Checking if the character is not just a space, but any whitespace, use this:

    It will replace any multiple whitespace character with a single space.

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

提交回复
热议问题