Write a function that accepts three string parameters, s, oldVal, newVal. Use iterator and erase and insert functions to replace all oldVal with newVal

C++ Primer exercises 9.4.3

#include <iostream>
#include <string>
using namespace std;
void replace_function(string &s,  const string &oldVal, const string &newVal) {
    
    //采用引用的形式,节约复杂度.除了s以外,其余两个应该为常量引用,不能更改
	int len1 = oldVal.size();
	string::iterator b = s.begin(); //用来遍历查找的迭代器,从首元素开始
	string::const_iterator  c1 = newVal.begin();
	string::const_iterator c2 = newVal.end();
	while (b<s.end()-len1+1)//当从b开始(包括b的位置)往后移动len-1个位置,还未到达end位置
	//这里我有些疑问:写成while(b+len1-1<s.end())就会出现报错???
	{
    
    
		if (s.substr(b - s.begin(), len1) == oldVal) {
    
    //如果子序列匹配
			b=s.erase(b, b + len1);//erase返回指向被删元素之后的迭代器.更新迭代器
			b=s.insert(b, c1, c2);//返回新添加的第一个选的的迭代器
			//s.replace(b - s.begin(), len1, newVal);9.44
			b += (len2 - 1);//到达这些新插入的元素的末尾
		}
		b++;//继续往后查询
	}
}
int main(){
    
    
	string s = "abcdefgbc";
 	string oldval = "bc";
 	string newval = "xyz";
	replace_function(s, oldval, newval);
	cout << s;
	return 0;
}

Guess you like

Origin blog.csdn.net/qq_42110350/article/details/114065277