user10049461
user10049461

Reputation: 55

Remove spaces from string not taking effect

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());

Upvotes: 3

Views: 101

Answers (3)

L. F.
L. F.

Reputation: 20579

For the benefit of future readers: in C++20, we have unified erasure, so we can simply use

std::erase_if(s, [](unsigned char c) { return !std::isalpha(ch); });

(See Do I need to cast to unsigned char before calling toupper(), tolower(), et al.? for why unsigned char should be used)

Upvotes: 0

Chris Dodd
Chris Dodd

Reputation: 126213

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); });

Upvotes: 3

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385164

So you replaced the characters you don't want with '\0'.

Then you removed all ' ' characters.

That last stage presumably should involve '\0'

Upvotes: 1

Related Questions