How to remove all the occurrences of a char in c++ string
Solution 1:
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];
Solution 2:
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());
Solution 3:
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;
}
Solution 4:
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());
Solution 5:
Starting with C++20, std::erase()
has been added to the standard library, which combines the call to str.erase()
and std::remove()
into just one function:
std::erase(str, 'a');
The std::erase()
function overload acting on strings is defined directly in the <string>
header file, so no separate includes are required. Similiar overloads are defined for all the other containers.