c++primer 4th edithon 第324页的一个练习题(9.43和9.44)

c++primer 4th edithon 第324页的一个练习题(9.43和9.44)_第1张图片

下标的方法:

9.43题

#include 
#include 
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 :"<

9.44题

迭代器的方法:

#include 
#include 
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 <

 

你可能感兴趣的:(c++)