天天看點

金海佳學C++primer 練習9.44string中替換oldVal->newVal(using replace)今天舞台上的你美到讓我心跳加速。

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 = ; i < len; i++) {
        int cnt = ;
        if(s[i] == oldVal[cnt]) {
            int j = ;
            for(j = ; 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
           

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

繼續閱讀