I’ve been working on this algorithm in C# to take a given string, remove any spaces, then return the result.
The algorithm works fine IF the first character in a given string is NOT a space. But if there is a space as the first character, the string returned contains the correct amount of characters but, the characters are “blank”, at least when printed to the console.
public static string RemoveSpaces(string arg)
{
char[] temp = arg.ToCharArray();
int newLength = 0;
//Calculate number of characters that arent spaces.
for (int e = 0; e < temp.Length; e++)
{
if (temp[e] != ' ')//If not a space,
{
newLength++;//then increment number of characters.
}
}
//Now use that number as size in new array
char[] newString = new char[newLength];
//Copy characters that arent spaces to the new char array.
for (uint e = 0, e2 = 0; e < temp.Length; e++, e2++)
{
//NOTE: e2 (and e) is a uint because it can end up negative for a
//short period.
if (temp[0] == ' ')//If the FIRST element is a space
{
e2--;//Then dont let e2 be "truely" incremented in next cycle.
continue;
//e (and e2) will now be incremented by the loop.
//but since we just decremented e2 it will be 1 behind e.
//So we wont be skipping an element in newString if
//we arent going to copy anything to that element.
//Same thing happens in the other if statement below.
//(Where the copying really happens)
}
if (temp[e] != ' ')//If element e is NOT a space,
{
newString[e2] = temp[e];//then copy that element to newString.
}
else//If element e IS a space
{
e2--;//Then dont let e2 be truely incremented in next cycle.
//Cycle is complete so no use for continue; here.
}
}
return new string(newString);//Done!
}
Don’t increment
e2in every iteration, increment it only when the character is not a space.Try this: