There is much easier way how to do that:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s("Your homework is bad. Really bad.");
while (s.find("bad") != string::npos)
s.replace(s.find("bad"), 3, "good");
cout << s << endl;
return 0;
}
output:
Your homework is good. Really good.
But watch out for case when the needle is a substring of the new value. In that case you might want to be shifting the index to avoid an infinite loop; example:
string s("Your homework is good. Really good."),
needle("good"),
newVal("good to go");
size_t index = 0;
while ((index = s.find(needle, index)) != string::npos) {
s.replace(index, needle.length(), newVal);
index += newVal.length();
}
cout << s << endl;
outputs
Your homework is good to go. Really good to go.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…