The C + + string provides the Replace method to implement the replacement of the string, but the string does not implement the function of replacing a string in the string, which is what we're doing today. First we understand the concept that string replaces all strings, substituting "21" for all "12" of the "12212" string, and what the result is.
Can be 22211, can also be 21221, sometimes the application of different scenarios, you will want to get different results, so both of the answers are implemented, the code is as follows:
#include <</span>string>
#include <</span>iostream>
using namespace Std;
string& Replace_all (string& str,const string& old_value,const)
{
while (true) {
String::size_type POS (0);
if ((Pos=str.find (Old_value))!=string::npos)
Str.replace (Pos,old_value.length (), new_value);
else break;
}
return str;
}
string& replace_all_distinct (string& str,const string& old_value,const)
{
For (String::size_type POS (0); Pos!=string::npos; Pos+=new_value.length ()) {
if ((Pos=str.find (Old_value,pos))!=string::npos)
Str.replace (Pos,old_value.length (), new_value);
else break;
}
return str;
}
int main ()
{
cout << Replace_all (String ("12212"), "a", "a" << Endl;
cout << replace_all_distinct (String ("12212"), "a", "a" << Endl;
}