Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove all the occurrences of a char in c++ string

Tags:

c++

stl

People also ask

How do you remove all occurrences of a substring from a string?

Example 1: Input: s = "daabcbaabcbc", part = "abc" Output: "dab" Explanation: The following operations are done: - s = "daabcbaabcbc", remove "abc" starting at index 2, so s = "dabaabcbc". - s = "dabaabcbc", remove "abc" starting at index 4, so s = "dababc".

What function can be used to remove all occurrences of the character from a string?

Remove All Occurrences of a Character From a String in Python Using the translate() Method. We can also use the translate() method to remove characters from a string. The translate() method, when invoked on a string, takes a translation table as an input argument.


Basically, replace replaces a character with another and '' is not a character. What you're looking for is erase.

See this question which answers the same problem. In your case:

#include <algorithm>
str.erase(std::remove(str.begin(), str.end(), 'a'), str.end());

Or use boost if that's an option for you, like:

#include <boost/algorithm/string.hpp>
boost::erase_all(str, "a");

All of this is well-documented on reference websites. But if you didn't know of these functions, you could easily do this kind of things by hand:

std::string output;
output.reserve(str.size()); // optional, avoids buffer reallocations in the loop
for(size_t i = 0; i < str.size(); ++i)
  if(str[i] != 'a') output += str[i];

The algorithm std::replace works per element on a given sequence (so it replaces elements with different elements, and can not replace it with nothing). But there is no empty character. If you want to remove elements from a sequence, the following elements have to be moved, and std::replace doesn't work like this.

You can try to use std::remove() together with str.erase()1 to achieve this.

str.erase(std::remove(str.begin(), str.end(), 'a'), str.end());

Using copy_if:

#include <string>
#include <iostream>
#include <algorithm>
int main() {
    std::string s1 = "a1a2b3c4a5";
    std::string s2;
    std::copy_if(s1.begin(), s1.end(), std::back_inserter(s2),
         [](char c){ 
                std::string exclude = "a";
                return exclude.find(c) == std::string::npos;}
    );

    std::cout << s2 << '\n';
    return 0;
}

string RemoveChar(string str, char c) 
{
   string result;
   for (size_t i = 0; i < str.size(); i++) 
   {
          char currentChar = str[i];
          if (currentChar != c)
              result += currentChar;
   }
       return result;
}

This is how I did it.

Or you could do as Antoine mentioned:

See this question which answers the same problem. In your case:

#include <algorithm>
str.erase(std::remove(str.begin(), str.end(), 'a'), str.end());