Austin
Austin

Reputation: 7359

Remove first char in string if found

In C++, if I have string 'aasdfghjkl' how, for instance, can I check to see if there's an 'a', and if so remove only the first occurrence of it?

I tried find() and then templetters.erase('a') but I think I need to already know the position for that to work.

Upvotes: 5

Views: 9573

Answers (1)

Shreevardhan
Shreevardhan

Reputation: 12651

You can use

auto it = std::find(s.begin(), s.end(), 'a');
if (it != s.end())
    s.erase(it);

EDIT: Alternative for std::string container only

auto pos = s.find('a');
if (pos != std::string::npos)    
    s.erase(pos);

Upvotes: 11

Related Questions