金海佳学C++primer 练习9.44

来源:互联网 发布:泛泰主义知乎 编辑:程序博客网 时间:2024/06/01 07:36

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: jinwanglangjiaold: hainew: wanglangjinwanglangjia

今天舞台上的你美到让我心跳加速。