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

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];

Leave a Comment

error code: 523