Delete All the Occurrence of A Character From A String in C++


    string str = "aaabcdeaaaa";
    str.erase(remove(str.begin(), str.end(), 'a'), str.end());

str.erase takes 2 arguments:

  1. Iterator 1 -> from which delete will be started
  2. 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:

  1. Beginning of the range
  2. end of the range
  3. 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');

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 :

  1. All the occurrence of a is removed
  2. move the rest of the characters in front after deleting
  3. 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!