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?
strip() Python String strip() function will remove leading and trailing whitespaces. If you want to remove only leading or trailing spaces, use lstrip() or rstrip() function instead.
String result = str. trim(); The trim() method will remove both leading and trailing whitespace from a string and return the result.
std::string::erase
returns an iterator, but you don't have to use it. Your original string is modified.
string removeSpaces(string input)
{
input.erase(std::remove(input.begin(),input.end(),' '),input.end());
return input;
}
std::remove_if along with erase
would be much easier (see it live):
input.erase(remove_if(input.begin(), input.end(), isspace),input.end());
using std::isspace had the advantage it will capture all types of white space.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With