下标的方法:
9.43题
#include <iostream>
#include <string>
using namespace std;
void replace_(string &s,const string &oldval,const string & newval)
{
for(size_t i = 0;i != s.size(); ++ i)
{
if(s[i] == oldval[0])
{
string temp(s,i,oldval.size());
cout << "Temp is:"<< temp << endl;
if(temp == oldval)
{
s = s.erase(i,oldval.size());
s = s.insert(i,newval);
cout << "old i is:" << i << endl;
i = i + newval.size() - 1;
cout << "new i is :"<<i <<endl << endl;
if(i == s.size())
{cout << "yes,break it"<<endl << endl;break;}
}
}
}
}
int main()
{
string oldval{"tho"};
string s{"asdfasthoasdfthoasdstho"},ss;
string newval{"thouth"};
replace_(s,oldval,newval);
return 0;
}
9.44题
迭代器的方法:
#include <iostream>
#include <string>
using namespace std;
//replace oldval by newval object to s1
void replace_(string &s1,const string & oldval,const string & newval)
{
for(string::iterator it = s1.begin();it != s1.end() ; ++ it)
{
if(*it == *oldval.begin())
{
string new_str(it,it + oldval.size());
if(new_str == oldval)
{
it = s1.erase(it,it+oldval.size());
it = s1.insert(it,newval.begin(),newval.end());
it += 5;
}
}
}
return ;
}
int main()
{
string s1 = "asdfasdfthoasdfthoasftho";
string oldval = "tho";
string newval = "though";
unsigned cnt = 1;
cout << s1 <<endl;
replace_(s1,oldval,newval);
cout << s1 <<endl;
return 0;
}