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

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

    try this method

    private string removeNestedWhitespaces(char[] st)
    {
        StringBuilder sb = new StringBuilder();
        int indx = 0, length = st.Length;
        while (indx < length)
        {
            sb.Append(st[indx]);
            indx++;
            while (indx < length && st[indx] == ' ')
                indx++;
            if(sb.Length > 1  && sb[0] != ' ')
                sb.Append(' ');
        }
        return sb.ToString();
    }
    

    use it like this:

    string test = removeNestedWhitespaces("1 2 3  4    5".toCharArray());
    

提交回复
热议问题