c++ - 用空格替换 std::string 中的特定字符

标签 c++ string parsing stdstring

以下代码从 char 数组中正确删除了标点符号:

#include <cctype>
#include <iostream>

int main()
{
    char line[] = "ts='TOK_STORE_ID'; one,one, two;four$three two";
    for (char* c = line; *c; c++)
    {
        if (std::ispunct(*c))
        {
            *c = ' ';
        }
    }
    std::cout << line << std::endl;
}

如果 linestd::string 类型,这段代码会是什么样子?

最佳答案

如果您只是更喜欢使用 STL 算法,它看起来像下面这样

#include<algorithm>

std::string line ="ts='TOK_STORE_ID'; one,one, two;four$three two";

std::replace_if(line.begin() , line.end() ,  
            [] (const char& c) { return std::ispunct(c) ;},' ');

或者如果你不想使用STL

只需使用:

std::string line ="ts='TOK_STORE_ID'; one,one, two;four$three two";
std::size_t l=line.size();
for (std::size_t i=0; i<l; i++)
{
    if (std::ispunct(line[i]))
    {
        line[i] = ' ';
    }
}

关于c++ - 用空格替换 std::string 中的特定字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18546386/

相关文章:

c++ - 启用视觉样式后我可以覆盖控件的颜色吗?

c++ - 继承和属性打包

c - 如何使用 sscanf 读取带有空格和数字的字符串?

php - 弄清楚一个词出现了多少次

java - 在字符串标记器 JAVA 中作为分隔符的字符集

c++ - 查找单个字符串中重复次数最多和次多的字符

c++ - 在 Linux 中使用命名管道的简单客户端/服务器程序

用于 RSS 提要解析的 Objective-C 库?

php - DOMXpath 移除标签

php - 如何从以加号 (+) 开头的行创建段落