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 < 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 > 1 && sb.Length > 0)
sb.Append(" ");
//Append the non space character
sb.Append(longChars[i]);
//Reset the space count
spaceCount = 1;
}
return sb.ToString();
}