c++ - 删除C++字符串中的字符

标签 c++

我在 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::isalnumstd::isspace 的行为取决于当前的语言环境。

关于c++ - 删除C++字符串中的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19641469/

相关文章:

c++ - 如何取消引用在 C++ 中通过引用传递的指针?

c++ - 当跨构造函数边界抛出异常时,borland C++ 编译器不会撤消内存分配?

c++ - <eof> 附近的 lua 函数参数

c++ - `const int <variable>` 不能出现在常量表达式中

php - 如何用 C++ 扩展 PHP?

c++ - 创建一个可以是多种类型的 C++ 数组

c++ - 在 mat vector 中存储图像

c++ - 应使用哪种数据结构 multimap、boost::bimap、multiset 或任何其他数据结构

c++ - 我应该为代码中的重复文字定义常量吗?

c++ - 在C++中对 vector 的内容进行排序