Delete All the Occurrence of A Character From A String in C++
# TL;DR
string str = "aaabcdeaaaa";
str.erase(remove(str.begin(), str.end(), 'a'), str.end());
cout<<str<<endl;
str.erase
takes 2 arguments:
- Iterator 1 -> from which delete will be started
- Iterator 2 -> to which delete operation will be ended
now we can’t delete by a character, and if we use
str.find()
and then delete every time it will be a O(n*n) operation.
Let’s take a closer look at remove()
which takes 3 arguments:
- Beginning of the range
- end of the range
- value that needs to be removed in this range
it doesn't resize the string or vector, for example:
string str = "aaabaacaade"; remove(str.begin(), str.end(), 'a'); cout<<str<<endl;
though we expect output like bcde
only, but in reality, the output is bcdeaacaade
, it returns the position 4 (str.begin() + 4
) and changes the string str in a way that :
- All the occurrence of a is removed
- move the rest of the characters in front after deleting
- do not change the size of the string, keep the rest of the string untouched
so we can combine the erase and replace and get the desired output in an efficient way!