Remove extra spaces from a string without using Regex or any internal library methods The objective is to remove extra spaces from the below string:


  "   Today   it  is     going    to  rain.     "


so it looks like below


  "Today it is going to rain."


Please determine if the code will perform well and if there is a better solution (NO REGEX or LAMBDA).

static string CompactStringPerfect()
{  
    string longString = "   Today   it  is     going    to  rain.     ";  

    StringBuilder sb = new StringBuilder();
    char[] longChars = longString.ToCharArray();

    int spaceCount = 0;

    //Using standard method with no library help
    for (int i = 0; i &lt; longChars.Length; i++)
    {
        //If space then keep a count and move on until nonspace char is found
        if (longChars[i] == 32)
        {
            spaceCount++;
            continue;
        }

        //If more than one space then append a single space  
        if (spaceCount &gt; 1 &amp;&amp; sb.Length &gt; 0)
            sb.Append(" ");

        //Append the non space character
        sb.Append(longChars[i]);

        //Reset the space count
        spaceCount = 1;
    }
    return sb.ToString();
}
A few things to point out.


char[] longChars = longString.ToCharArray();



strings in C# are array-like, and can be indexed directly. We don't need to convert it into a char[].


int spaceCount = 0;



We don't really need to keep track of how many spaces so much as whether the last character was a space. Therefore, this can become a boolean flag instead.


if (longChars[i] == 32)



This line has a magic number (32), and that makes it a little harder to understand. I'm guessing it's the Unicode number for the space character, but the fact that I have to guess makes it bad. Better would be: if(longChars[i] == ' '), but best would be: if(Char.IsWhiteSpace(longChars[i])). That catches all potential whitespace characters, and will be more robust. Also, it makes your intention much clearer.


if (spaceCount &gt; 1 &amp;&amp; sb.Length &gt; 0)
    sb.Append(" ");



I always recommend using braces in light of goto fail.


//Reset the space count
spaceCount = 1;



This confuses me. You say you are "resetting" the space count, but the original value was 0, not 1, so I might (incorrectly) think this is a bug and try to fix it. The root of this issue lies in how you are tracking spaces.

So incorporating those suggestions, here's what I come up with:

public static string Despace(string longString) {
    StringBuilder sb = new StringBuilder();
    bool lastWasSpace = true; // True to eliminate leading spaces

    for(int i = 0; i &lt; longString.Length; i++) {
        if(Char.IsWhiteSpace(longString[i]) &amp;&amp; lastWasSpace) {
            continue;
        }

        lastWasSpace = Char.IsWhiteSpace(longString[i]);

        sb.Append(longString[i]);
    }

    // The last character might be a space
    if(Char.IsWhiteSpace(sb[sb.Length - 1])) {
        sb.Remove(sb.Length - 1, 1);
    }

    return sb.ToString();
}