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

查看:85
本文介绍了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.

(我有机会获得提振。)

(I have access to Boost.)

推荐答案

至于其他的答案表明,你可以使用各种替换方法。然而,这些方法有字符串多次(一次每个字符)扫描的缺点。我会建议滚动您自己更换方法,如果你在乎速度:

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天全站免登陆