我有一个std::string,如何用:替换%%字符?

std::replace( s.begin(), s.end(), ':', '%%' );
上面的代码不起作用:


  错误没有实例与论据列表匹配


谢谢!

最佳答案

不幸的是,无法一次替换所有:字符。但是您可以像这样循环执行:

string s = "quick:brown:fox:jumps:over:the:lazy:dog";
int i = 0;
for (;;) {
    i = s.find(":", i);
    if (i == string::npos) {
        break;
    }
    s.replace(i, 1, "%%");
}
cout << s << endl;


该程序prints

quick%%brown%%fox%%jumps%%over%%the%%lazy%%dog


如果只需要替换第一个冒号,则可以单独使用循环的主体,而不必围绕它。

09-10 04:31
查看更多