I need to be able to get rid of spaces in a string. All strings are representations of functions:

3 * x ( 1 ) + 1 * x ( 3 ) + 6 * x ( 2 ) – 10 * X ( 0 )

and i have to build a trim function that turns the above into:

3*x(1)+1*x(3)+6*x(2)–10*X(0)

i have tried the below but it just copies the string.

``````int main (void)
{
string function = "3 * x ( 1 ) + 1 * x ( 3 ) + 6 * x ( 2 ) – 10 * X ( 0 )";
cout << function << endl;
trim(function);
cout << function;
system("pause");

}

void trim(string& s)
{
int length = s.length();
string copy;
copy = s;

int k = 0;
for (int i = 0; i<length; i++)
{
//position of s
if (copy[i] = ' ')
{
continue;
}
else
{
s[k] = copy[i];
k++;
}

}

}``````

Any help would be appreciated!

The following code should work:

``````void trim(string & s)
{
int strlen = s.length();
string tmp;
for(int i = 0; i < strlen; i++)
if(s[i] != ' ') tmp += s[i];
s = tmp;
}``````

> Why are you using a seperate counter 'k', you can just add something to a string by using the '+' operator ...

> Also avoid the use of `system("pause");` (look here for the reasons), it's better to use `cin.get();` instead ...

> Edit:: Your mistake is on the line where you say: `if (copy[i] = ' ')` , it has to be `if (copy[i] == ' ')` ,
if you write `if (copy[i] = ' ')` , `copy[i]` will get the value `' '` , so the condition is always true, then you're running the `continue` statement everytime which is just skipping to the next `i` of the loop ...

But because the string copy is in the beginning (of your function) just an exact copy of the string s, the string s' value will remain the same :) ...

> Edit:: You're just overwriting string s, that causes a bad result, the last part of the 'trimmed' string will be the same as the original, but it still contains the whole (trimmed) expression ... ==> If someone can explain this in a better way please do so, as I'm not very good at it :P ...

Thanks a lot Tux, i cant believe i missed the missing equal in the condition statement. Yeah i realized that even with that correction, my way still had all the same junk at the end of the string from the last one.

Thanks again.