我在 C++ 中有以下形式的字符串
string variable1="This is stackoverflow \"Here we go "1234" \u1234 ABC";
现在在这个字符串中,我想删除除字母表(从 a 到 b,以及 A 到 B)和数字之外的所有字符。这样我的输出就变成了
variable1="This is stackoverflow Here we go 1234 u1234 ABC";
我尝试使用指针检查每个字符,但发现效率很低。是否有使用 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()
);
请注意 std::isalnum
和 std::isspace
的行为取决于当前的语言环境。
关于c++ - 删除C++字符串中的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19641469/