Replace the character with two other

会有一股神秘感。 提交于 2019-12-13 03:59:35

问题


I have a std::string, how can i replace : character with %%?

std::replace( s.begin(), s.end(), ':', '%%' ); this code above doesn't work:

error no instance matches the arguement list

Thanks!


回答1:


Unfortunately, there is no way to replace all : characters in one shot. But you can do it in a loop, like this:

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;

This program prints

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

If you need to replace only the first colon, then use the body of the loop by itself, without the loop around it.



来源:https://stackoverflow.com/questions/14113173/replace-the-character-with-two-other

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!