Boris
Boris

Reputation: 369

Replace the character with two other

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!

Upvotes: 0

Views: 1079

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726839

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.

Upvotes: 8

Related Questions