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

Remove numbers and keep underscore from string in C++

我有这段代码,但它输出 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;