I want to remove all whitespace from a string. Here's what I have so far:
(expression is the string)
1 2 3 4 5 6
for (int i = 0; i < expression.length(); i++) {
if (expression[i] == ' ') {
expression.erase(i, 1);
i--;
}
}
But this just removes everything, whitespace or not, starting from the first whitespace. (e.g. If I input "1 + 1" it will give me just "1")
I've tried searching it up on Google and trying the answers. But none seemed to work. This expression.erase(std::remove(expression.begin(),expression.end(),' '),expression.end());
does the same thing as my code above. And this expression.erase(remove_if(expression.begin(), expression.end(), isspace), expression.end());
gives me an error (I'm running it in cpp.sh):
213:74: error: no matching function for call to 'remove_if(std::basic_string<char>::iterator, std::basic_string<char>::iterator, <unresolved overloaded function type>)'
213:74: note: candidate is:
In file included from /usr/include/c++/4.9/algorithm:62:0,
from 8:
/usr/include/c++/4.9/bits/stl_algo.h:926:5: note: template<class _FIter, class _Predicate> _FIter std::remove_if(_FIter, _FIter, _Predicate)
remove_if(_ForwardIterator __first, _ForwardIterator __last,
^
/usr/include/c++/4.9/bits/stl_algo.h:926:5: note: template argument deduction/substitution failed:
213:74: note: couldn't deduce template parameter '_Predicate'
Why isn't my code and the second solution working? Is there any alternative ways to do this? Thank you.