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?

Recommended Answers

All 2 Replies

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.

Thanks a lot!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.