string中替换oldVal->newVal(using replace)
Practice 9.44
#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;
void old2new_2(string & s, string oldVal, string newVal) {
int len = (int)s.length();
int len2 = (int)oldVal.length();
for(int i = 0; i < len; i++) {
int cnt = 0;
if(s[i] == oldVal[cnt]) {
int j = 0;
for(j = 0; i+j<len && cnt<len2; j++, cnt++) {
if(s[i+j] != oldVal[cnt]) break;
}
if(j == len2) {
s.replace(i,len2,newVal);
}
}
}
}
int main() {
string s, oldVal, newVal;
cin >> s >> oldVal >> newVal;
old2new_2(s,oldVal,newVal);
cout << "s: " << s << endl;
cout << "old: " << oldVal << endl;
cout << "new: " << newVal << endl;
cout << s << endl;
}
Output
s: jinwanglangjia
old: hai
new: wanglang
jinwanglangjia
今天舞台上的你美到让我心跳加速。