C ++字符替换 [英] C++ character replace

查看:124
本文介绍了C ++字符替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

更换字符串中的字符的最好方法是什么?

What is the best way to replace characters in a string?

具体来说:

"This,Is A|Test" ----> "This_Is_A_Test"

我要替换所有的逗号,空格和|

I want to replace all commas, spaces, and "|" with underscores.

(我可以访问Boost。)

(I have access to Boost.)

推荐答案

如其他答案所示,您可以使用各种 replace 方法。然而,这些方法具有扫描字符串多次(每个字符一次)的缺点。如果你关心速度,我建议你滚动自己的替换方法:

As the other answers indicated, you can use the various replace methods. However, these approaches have the downside of scanning the string multiple times (one time for each character). I would recommend rolling your own replace method, if you care about speed:

void beautify(std::string &s) {
    int i;
    for (i = 0; i < s.length(); ++i) {
        switch (s[i]) {
        case ' ':
        case ',':
        case '|':
            s[i] = '_';
        }
    }
}

这篇关于C ++字符替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆