我对 C++ 中的 STL 很陌生,即使在几个小时后也无法获得正确的输出。
int main()
{
std::string str = "Hello8$World";
replace(str.begin(), str.end(), ::isdigit, " ");
replace(str.begin(), str.end(), ::ispunct, " ");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
如果上述方法有效,我会非常高兴,但事实并非如此。
全部与lambda 函数合而为一,更像C++14风格:
#include <iostream>
#include <string>
#include <algorithm>
int main() {
std::string str = "Hello8$World";
std::replace_if(str.begin(), str.end(), [](auto ch) {
return ::isdigit(ch) || ::ispunct(ch);
}, ' ');
std::cout << str << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这样你就不会在字符串上迭代两次。