I am currently learning C++. I am trying to code a method to remove white spaces form a string and return the string with no spaces This is my code:
string removeSpaces(string input)
{
int length = input.length();
for (int i = 0; i < length; i++) {
if(input[i] == ' ')
input.erase(i, 1);
}
return input
}
But this has a bug as it won't remove double or triple white spaces. I found this on the net
s.erase(remove(s.begin(),s.end(),' '),s.end());
but apparently this is returning an iterator (if I understand well)
Is there any way to convert the iterator back to my string input?
Most important is this the right approach?
s. So it doesn't matter that it returns an iterator. Just changesand returns.std::vector,std::stringhas a default (ofstd::string::nposwhich acts as a sentinel for "until the end") for the second parameter, so you can simplys.erase(remove(s.begin(),s.end(),' '));.s.end()at the end of the expressions.erase(remove(s.begin(),s.end(),' '),s.end());is just a sentinel that tells me when the string is finished right?eraseto remove the elements all the way to the end of thestring, which is the default behaviour forstd::string::eraseanyway....