I'm trying to remove all characters and spaces except letters. But the "erase spaces" part doesn't take effect, it will only take effect if I comment out the remove characters part.
for (int i = 0; i < s.size(); i++)
{
if (!(s[i] >= 'a' && s[i] <= 'z' || s[i] >= 'A' && s[i] <= 'Z'))
{
s[i] = '\0';
}
}
s.erase(remove(s.begin(), s.end(), ' '), s.end());
You're replacing all the non-alphabetic characters with NULs, then removing all the spaces. Since NULs are not spaces, this latter step does nothing. If you change the assignment in the loop to
s[i] = ' ';
you would instead replace them with spaces, which would then be removed by the eraser(remove
If you want to make the code more readable, you could replace the complex if with
if (!isalpha(s[i]))
or you could even replace the whole thing with
s.erase(remove_if(s.begin(), s.end(), [](char ch){ return !isalpha(ch); });
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