題意不難理解,但是一開始還是沒有看清楚題目。Replace the first occurrence of the find string within the text by the replace-by string, then try to perform the same replacement again on the new text. Continue until the find string no longer occurs within the text, and then move on to the next rule.這個地方我貢獻了幾次TL。它的意思是替換完第n個字符串後,繼續判斷是否還能被這個字符串替換,否則移至下一個。
#include <iostream> #include <cstdio> #include <string> using namespace std; int main() { //freopen("in.txt","r",stdin); while(1) { int n; scanf("%d",&n); if(n==0) break; string str1[12]; string str2[12]; getchar(); for(int i=0; i<n; i++) { getline(cin,str1[i]); getline(cin,str2[i]); } string str3; getline(cin,str3); for(int i=0; i<n; i++) while(1) { int index=str3.find(str1[i]); //查找要替換的字符串位置,沒有返回string::npos if(index==string::npos) break; str3=str3.replace(index,str1[i].length(),str2[i]); //replace函數直接替換,或者用erase和insert也行 //str3.erase(index,str1[i].length()); //str3.insert(index,str2[i]); } cout<<str3<<endl; } return 0; }