如何将 std::string 中的所有非字母字符(数字和特殊字符)替换为空格

How to replace all non alpha characters (digits and special characters) from std::string with a space

本文关键字:数字 字符 特殊字符 空格 替换 string std      更新时间:2023-10-16

我对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(一个接受一个参数并返回 truefalse 的函数)和迭代器中每个位置的对象的基础类型(对于字符串来说,这是一个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,' ');

它工作得很好(实时示例)。