0

I am trying to replace all % with %%, because I want to write a string to a file using the fprintf_s function.
Yet, I done this:

void replace(std::string& target, const std::string oldstr, const std::string newstr) {
            unsigned int x;
            while(x = target.find(oldstr), x != std::string::npos) {
                    target.erase(x, oldstr.length());
                    target.insert(x, newstr);
            }
    } 

string text = "% % %";
replace(text, "%", "2A");
cout << text;

The result is "2A 2A 2A"

But when I try doing the follwing the program loops forever:

string text = "% % %";
replace(text, "%", "%%");
cout << text;

Can you guys help me find out how to fix this?

Edited by Legend32A: n/a

2
Contributors
2
Replies
3
Views
6 Years
Discussion Span
Last Post by Legend32A
0

You are perpetually increasing the size of the string (and number of %'s in it).
FOr instance:

original: "% % %"
find("%") -> 0
replace("%%") -> "%% % %"
find("%") -> 0
replace("%%") -> "%%% % %"
find("%") -> 0
replace("%%") -> "%%%% % %"

And so on.
My suggestion would be to scan the string from right to left generating a new string as you go replacing the target strings with the transformations.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.