IF a string may include several un-necessary elements, e.g., such as @, #, $,%.
How to find them and delete them?
I know this requires a loop iteration, but I do not know how to represent sth such as @, #, $,%.
If you can give me a code example, then I will be really appreciated.
Cub*_*bbi 13
通常的标准C++方法是擦除/删除习惯用法:
#include <string>
#include <algorithm>
#include <iostream>
struct OneOf {
std::string chars;
OneOf(const std::string& s) : chars(s) {}
bool operator()(char c) const {
return chars.find_first_of(c) != std::string::npos;
}
};
int main()
{
std::string s = "string with @, #, $, %";
s.erase(remove_if(s.begin(), s.end(), OneOf("@#$%")), s.end());
std::cout << s << '\n';
}
Run Code Online (Sandbox Code Playgroud)
是的,boost提供了一些简洁的方法来编写它,例如使用boost :: erase_all_regex
#include <string>
#include <iostream>
#include <boost/algorithm/string/regex.hpp>
int main()
{
std::string s = "string with @, #, $, %";
erase_all_regex(s, boost::regex("[@#$%]"));
std::cout << s << '\n';
}
Run Code Online (Sandbox Code Playgroud)