c++ primer 第九章答案
9.44 编写一个函数,接受三个string参数s,oldVal和newVal.使用迭代器及insert和erase函数将s中所有oldVal替换为newVal。测试你的程序,用它替换通用的简写形式,如,将“tho”替换为“though”,将“thru”替换为“through”
原题是要求使用replace + 下标
下面解法是使用 replace + find函数
#include <iostream>
#include <algorithm>
#include<string>
#include<array>
#include<vector>
#include<forward_list>
#include<deque>
#include<list>
using namespace std;
void replaceStrByReplace(string& s, string& oldVal, string& newVal)
{
int old_size = oldVal.size();
int new_size = newVal.size();
int pos;
auto iter_s = s.begin();
while (pos = s.find(oldVal), pos != -1)
{
s.replace(pos, old_size, newVal);
}
}
void test943()
{
string str = "abc thru efg thru";
string oldStr = "thru";
string newStr = "through";
replaceStrByReplace(str, oldStr, newStr);
cout << str << endl;
}
int main() {
test943();
cout << a << endl;
system("pause");
return 0;
}

浙公网安备 33010602011771号