如何将 std::string 中的所有非字母字符(数字和特殊字符)替换为空格
How to replace all non alpha characters (digits and special characters) from std::string with a space
我对C++的STL很陌生,即使在几个小时后也无法获得正确的输出。
int main()
{
std::string str = "Hello8$World";
replace(str.begin(), str.end(), ::isdigit, " ");
replace(str.begin(), str.end(), ::ispunct, " ");
return 0;
}
如果上述方法有效,我会很高兴,但事实并非如此。
所有这些都与 lambda 函数合二为一,更C++14-ish:
#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;
}
这样,您就不会在字符串上迭代两次。
使用谓词的函数名称是std::replace_if
,并且您想要替换字符,因此' '
,而不是" "
- 这是char const*
:
#include <iostream>
#include <string>
#include <algorithm>
int main()
{
std::string str = "Hello8$World";
std::replace_if(str.begin(), str.end(), ::isdigit, ' ');
std::replace_if(str.begin(), str.end(), ::ispunct, ' ');
std::cout << str << std::endl;
return 0;
}
在这种情况下
,您需要使用 replace_if
函数,因为您正在检查条件。Cppreference对此有很好的解释。replace_if
的最后两个参数是 UnaryPredicate(一个接受一个参数并返回 true
或 false
的函数)和迭代器中每个位置的对象的基础类型(对于字符串来说,这是一个char
,而不是一个字符串)。
int main()
{
std::string str="Hello8$World";
std::cout << str << std::endl;
std::replace_if(str.begin(), str.end(), ::isdigit, ' ');
std::replace_if(str.begin(), str.end(), ::ispunct, ' ');
std::cout << str << std::endl;
return 0;
}
您使用了错误的函数。 std::replace
需要两个迭代器,一个旧值和一个新值。 std::replace_if
需要两个迭代器一个函数和一个新值。 您还需要使用 ' '
not " "
,因为字符串迭代器指向的类型是字符而不是字符串。 如果将其更改为
replace_if(str.begin(),str.end(),::isdigit,' ');
replace_if(str.begin(),str.end(),::ispunct,' ');
它工作得很好(实时示例)。
相关文章:
- 递归形成字符串中所有数字字符的中间和?
- C++ 从 std::string 中删除所有非数字字符
- 如何返回一串字母数字字符中的最大值(例如-1A003B3)?
- 有没有办法将最初作为字符串输入的数字字符数组复制到双向链表中
- 如何使用 c++ 将数字字符转换为字符串
- 从字符数组中修剪非字母数字字符的功能
- 使用find_if和isalnum在字符串中找到字母数字字符
- 循环直到整数输入在所需范围内无法处理非数字字符输入
- 确保字符串只包含字母数字字符的更好方法
- 用C++计算文本文件中的字母数字字符
- 使用cctype库搜索函数,以查找某个范围内的数字字符数
- 在读取C++行时过滤非字母数字字符
- C++ 如何从标准输入加载到最多 5 个字母数字字符的字符数组
- 如何知道小部件是否只接受数字字符
- 在 C++ STL 中,如何使用 regex_replace 从 std::string 中删除非数字字符
- i18n 去除非字母数字字符的友好方式
- 将字符数组拆分为字母数字字符和非字母数字字符
- 将多数字字符数转换为整数
- 在检测字符串是否包含数字字符时,这有什么问题
- 如何检测QString是否由所有数字字符组成