字符串替换replace函数

    科技2022-07-10  170

    replace函数

    例题:将zlx ,zzx和highschoolgrandpa替换成%%%

    #include <iostream> #include <cstdio> #include <cstring> #include <string> #include <cmath> #include <algorithm> using namespace std; int main (){ string str1; string str2 = "zlx"; string str3 = "zzx"; string str4 = "highschoolgrandpa"; string str5 = "%%%"; int pos = 0; while(cin >> str1){ while( 1 ){ if( str1.find(str2) != string::npos ){ pos = str1.find(str2); str1.replace( pos, 3, str5);//将字符串str1 从pos位置开始的3个字符替换成str5 } else if( str1.find(str3) != string::npos ){ pos = str1.find(str3); str1.replace( pos, 3, str5); } else if( str1.find(str4) != string::npos){ pos = str1.find(str4); str1.replace( pos, 17, str5); } else break; } cout << str1 << endl; } return 0; }
    Processed: 0.013, SQL: 8