2017年11月26日 星期日

[C_ST85-易] 切割字串(C++)

[C_ST85-易] 切割字串

問題描述 :
一段文字中,找出特殊字串,是程式設計文字處理的基本技巧。 輸入 一個字串,找出字串中特殊的字串,其中特殊字串包含 /n, /t, /a, /b, // 等五種 , 剖析文字的內容,找到特定的字串,計算讀到幾個,並輸出結果。
輸入說明 :
輸入一列的 文字 ,
例如:
Today/nisagoodday./nIlike.
輸出說明 :
計算找到的特殊字串,並輸出個數結果
輸出為:
2
範例 :
輸入範例
輸出範例
Today/nisagoodday./nIlike.
2
Would/byoulike/njavaprogrammig/n?
3
Accidents/ncan be//occur/tanywhere around you home.
3
說明:
這裡有些小陷阱,如果出現//n,只用find()出來的結果,是2。
可是輸出期望,是1。
為了解決這個問題,就是找到後取代成"**",只要不是"//",當然要取代成"$$""%%""&&"...都可以。


  1. #include <iostream>  
  2. using namespace std;  
  3.   
  4. int main() {  
  5.     // [C_ST85-易] 切割字串  
  6.     string strInput;  
  7.     getline(cin, strInput);  
  8.     string strFind[5] = {"/n""/t""/a""/b""//"};  
  9.     int count = 0;  
  10.     for (int i = 0; i < 5; i++)  
  11.     {  
  12.         string findstr = strFind[i];  
  13.         string R = "**";  
  14.         int fpos = 0;  
  15.         while (1)  
  16.         {  
  17.             fpos = strInput.find(findstr, fpos);  
  18.               
  19.             if (fpos != string::npos)  
  20.             {  
  21.                 strInput.replace(fpos, findstr.size(), R);  
  22.                 fpos = fpos + findstr.size();  
  23.             }  
  24.             else  
  25.             {  
  26.                 break;  
  27.             }  
  28.             count++;  
  29.         }  
  30.     }  
  31.     cout << count << endl;  
  32.     return 0;  
  33. }  

沒有留言:

張貼留言