我在C++中有以下形式的字符串
string variable1="This is stackoverflow \"Here we go "1234" \u1234 ABC";
Run Code Online (Sandbox Code Playgroud)
现在在这个字符串中我想删除除字母(从a到b,A到B)和数字之外的所有字符.这样我的输出就变成了
variable1="This is stackoverflow Here we go 1234 u1234 ABC";
Run Code Online (Sandbox Code Playgroud)
我试图使用指针检查每个字符,但发现效率非常低.有没有一种使用C++/C实现相同目的的有效方法?
用途std::remove_if
:
#include <algorithm>
#include <cctype>
variable1.erase(
std::remove_if(
variable1.begin(),
variable1.end(),
[] (char c) { return !std::isalnum(c) && !std::isspace(c); }
),
variable1.end()
);
Run Code Online (Sandbox Code Playgroud)
请注意,当前区域设置的行为std::isalnum
和std::isspace
取决于当前区域设置.