Devesh Agrawal Devesh Agrawal - 1 year ago 91
C++ Question

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

I am using following:

replace (str1.begin(), str1.end(), 'a' , '')

But this is giving compilation error.

Answer Source

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:

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];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download