2017年11月26日 星期日

[C_ST41-中] 字串取代(C++)

[C_ST41-中] 字串取代

問題描述:
輸入三字串 P, Q, R ,將字串 P 中所有出現字串 Q 的部分取代成字串 R 。
輸入說明:
1. 鍵盤輸入字串 P, Q, R
2. 字串為 ASCII Code 組成,且區分大小寫
輸出說明:
輸出字串 P 中的字串 Q 被字串 R 取代後的結果
範例:
Sample InputSample Output
A boy picked a ball, and the ball was red.
ball
hat
A boy picked a hat, and the hat was red.
Sprint and HTC launch the first 4G handset in America -- and its got Android onboard.
HTC
Smart Phone
Sprint and Smart Phone launch the first 4G handset in America -- and its got Android onboard.
AAACCCCDDHHHI
CCCC
BB
AAABBDDHHHI


  1. #include <iostream>  
  2. #include<iomanip>    
  3. #include<string>  
  4.   
  5. using namespace std;  
  6.   
  7. int main() {  
  8.     // [C_ST41-中] 字串取代  
  9.     string P, Q, R;  
  10.     //將字串P中所有出現字串Q的部分取代成字串R  
  11.     getline(cin, P);  
  12.     getline(cin, Q);  
  13.     getline(cin, R);  
  14.     int fpos = 0;  //因為忘了設初始值而出錯
  15.     while(1)  
  16.     {  
  17.         fpos = P.find(Q, fpos); //在P字串中尋找子字串Q  
  18.         if(fpos != string::npos)  
  19.         {  
  20.             P.replace(fpos, Q.size(), R); //取代  
  21.             fpos = fpos + Q.size();  
  22.         }  
  23.         else  //如果找不到就跳出迴圈  
  24.         {  
  25.             break;  
  26.         }  
  27.     }  
  28.     cout << P << endl;  
  29.     return 0;  
  30. }  

沒有留言:

張貼留言