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

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

    Many answers are providing the right output but for those looking for the best performances, I did improve Nolanar's answer (which was the best answer for performance) by about 10%.

    public static string MergeSpaces(this string str)
    {
    
        if (str == null)
        {
            return null;
        }
        else
        {
            StringBuilder stringBuilder = new StringBuilder(str.Length);
    
            int i = 0;
            foreach (char c in str)
            {
                if (c != ' ' || i == 0 || str[i - 1] != ' ')
                    stringBuilder.Append(c);
                i++;
            }
            return stringBuilder.ToString();
        }
    
    }
    

提交回复
热议问题