Originally Posted by
salquestfl
Still, why to do replace_if, unique and erase when remove_if is what is needed?
Because remove_if does not work. I know because I nearly posted such an example, until I noticed that Swerve's sample result was "A tring of EX !", not "A tring of EX!". The space in between the 'X' and the '!' is due to the replacement with a space.
Originally Posted by
salquestfl
Then what is the need of unique and erase?
You either define the problem as
1. Replace unwanted characters by spaces OR
2. Remove unwanted characters
Your code and comments suggest you are trying to do problem 2.
You missed a third possibility, which is what Swerve stated in post #1: replace unwanted characters with a space character. That is, each region of consecutive unwanted spaces is to be replaced by a single space character.
Originally Posted by
salquestfl
Again, this problem is because you are adding the spaces in the first place and then trying to remove the exact same spaces.
No, I am only trying to remove duplicate spaces that were the result of replacing each unwanted character with space. The problem is due to an oversight in the use of std::unique. Nonetheless, I have proposed a better fix if this turns out to be a problem (it might actually be desirable), i.e., remove the duplicate unwanted characters first, and only then replace each remaining unwanted character with a space.
EDIT:
If you want a code example, this would be it:
Code:
#include <string>
#include <algorithm>
#include <iostream>
class MatchChars
{
public:
explicit MatchChars(const std::string& chars) : chars(chars) {}
bool operator()(char c) const
{
return chars.find(c) != std::string::npos;
}
bool operator()(char c1, char c2) const
{
return chars.find(c1) != std::string::npos
&& chars.find(c2) != std::string::npos;
}
private:
std::string chars;
};
int main()
{
std::string str = "A string of TEXT!";
const MatchChars match_chars("sT");
str.erase(std::unique(str.begin(), str.end(), match_chars), str.end());
std::replace_if(str.begin(), str.end(), match_chars, ' ');
std::cout << str << std::endl;
}
But I am not sure if this is what Swerve wants because the given sample output does not match the sample output produced by this program. If I am correct, a correct solution would be:
Code:
#include <string>
#include <algorithm>
#include <iostream>
class MatchChars
{
public:
explicit MatchChars(const std::string& chars) : chars(chars) {}
bool operator()(char c) const
{
return chars.find(c) != std::string::npos;
}
private:
std::string chars;
};
class IsDuplicateSpace
{
public:
bool operator()(char c1, char c2) const
{
return c1 == ' ' && c2 == ' '
}
};
int main()
{
std::string str = "A string of TEXT!";
std::replace_if(str.begin(), str.end(), MatchChars("sT"), ' ');
str.erase(std::unique(str.begin(), str.end(), IsDuplicateSpace()), str.end());
std::cout << str << std::endl;
}