c++ - 在 C++ 中从字符串中删除数字并保留下划线

标签 c++ string c++-standard-library

我有这段代码,但它输出 Hello World 不带下划线。如果我想输出Hello_World,我该怎么做?

string s = "Hello_World 1 2";
s.erase(remove_if(s.begin(), s.end(), [](char c) { return !isalpha(c); } ), s.end());

最佳答案

您可以通过向 std::remove_if 函数添加另一个条件来实现特定输出。

std::string s = "Hello_World 1 2";
s.erase( std::remove_if(s.begin(), s.end(),  [](char c) 
                       { 
                           return !isalpha(c) && c != '_';
                       }), 
                       s.end());
std::cout << s;

关于c++ - 在 C++ 中从字符串中删除数字并保留下划线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50418126/

相关文章:

c++ - 如何防止C/C++中的缓冲区溢出?

c++ - 将二维 vector 连接到左侧

c++ - 如何部署 C++ DLL

javascript - jquery从两个区域中删除字符串部分

c++ - 获取没有实例的 std::bitset 的大小

c++ - 为什么排序函数在全局命名空间中?

c++ - 使用 Crypto++ 就地 AES CBC/ECB 模式加密/解密

java - 从文本文件中删除评论

string - 我可以在 Perl 5 中为字符串创建文件句柄,我如何在 Perl 6 中做到这一点?

c++ - C++ 标准库中名为 "base"和 "basic"的类的约定是什么?