Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove spaces from string not taking effect

Tags:

c++

stdstring

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());
like image 584
user10049461 Avatar asked Jan 27 '26 22:01

user10049461


1 Answers

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); });
like image 178
Chris Dodd Avatar answered Jan 29 '26 11:01

Chris Dodd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!