Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove first char in string if found

Tags:

c++

string

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.

like image 252
Austin Avatar asked Dec 20 '22 02:12

Austin


1 Answers

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);
like image 81
Shreevardhan Avatar answered Jan 03 '23 04:01

Shreevardhan