string中替换oldVal->newVal
Practice 9.43
#include <iostream>
#include <queue>
#include <string>
#include <vector>
#include <algorithm>
#include <list>
#include <iterator>
#include <cmath>
#include <cstring>
#include <forward_list>
#include <sstream>
using namespace std;
bool ok(string::iterator it1, string s2) {
auto it2 = s2.begin();
while(it2 != s2.end()) {
if(*it1 != *it2) break;
it1++, it2++;
}
if(it2 == s2.end()) return true;
else return false;
}
void old2new(string & s, string oldVal, string newVal) {
auto it = s.begin();
int len_old = (int)oldVal.length();
while(it != s.end()) {
if(ok(it, oldVal)) {
s.erase(it,it+len_old);
s.insert(it,newVal.begin(),newVal.end());
}
else {
++it;
}
}
}
int main() {
string s, oldVal, newVal;
cin >> s >> oldVal >> newVal;
old2new(s,oldVal,newVal);
cout << "s: " << s << endl;
cout << "old: " << oldVal << endl;
cout << "new: " << newVal << endl;
cout << s << endl;
return 0;
}
Ouput
s: jinwanglangjia
old: hai
new: wanglang
jinwanglangjia
The world is his who enjoys it.