2017年11月26日 星期日

[C_ST63-易] 尋找單字中的母音字母數量(C++)

[C_ST63-易] 尋找單字中的母音字母數量

問題描述:
英文字母中有五個母音,分別是 a 、 e 、 i 、 o 、 u ,請寫一個程式,讓使用者可以輸入若干單字,並顯示這些單字內分別有幾個母音字母 ( 不分大小寫 )
輸入說明:
先輸入欲輸入的單字數量 N ,然後輸入單字,輸入完後按 Enter 及可以輸入下一個單字一直至輸入完畢。
輸出說明:
分別列出每個單字有多少個母音字母。
範例:
Sample Input:Sample Output:
1
abandon
abandon 3
輸出輸入測試資料 各五筆
inputoutput
2
machine
logistics
machine 3
logistics 3
2
extinguisher
distributor
extinguisher 5
distributor 4
3
facility
hazard
enhance
facility 3
hazard 2
enhance 3
1
customize
customize 4
4
defect
cylinder
component
automatic
defect 2
cylinder 2
component 3
automatic 5



  1. #include <iostream>  
  2. #include <ctype.h>  
  3. #include <stdio.h>  
  4. #include <string.h>  
  5. using namespace std;  
  6.   
  7. int main() {  
  8.     // [C_ST63-易] 尋找單字中的母音字母數量  
  9.     int N;  
  10.     int count = 0;;  
  11.     string vowel[5] = {"a""e""i""o""u"};  
  12.     string str_original; //原本的字串  
  13.     while(cin >> N)  
  14.     {  
  15.         for(int i = 0;i < N;i++)  
  16.         {  
  17.             cin >> str_original; //輸入原本的字串  
  18.             int len = str_original.size();   
  19.             //原本的字串的長度  
  20.             char original[len]; //原本的字元陣列  
  21.             char variety[len];  //變化後的字元陣列  
  22.             strcpy(original, str_original.c_str());    
  23.             //string to char  
  24.             //把原本的字元陣列統一轉成小寫,放入變化後的字元陣列內  
  25.             for(int j = 0; j < len;j++)  
  26.             {  
  27.                 variety[j] = (char)tolower(original[j]);  
  28.             }  
  29.             string str_variety(variety);//char to string  
  30.             //計算數量  
  31.             for(int j = 0; j < 5;j++) //五個母音  
  32.             {  
  33.                 int fpos = 0;  
  34.                 string v = vowel[j];  
  35.                 while(1)  
  36.                 {  
  37.                     fpos = str_variety.find(v, fpos);  
  38.                     if (fpos != -1) //fpos != string::npos  
  39.                     {  
  40.                         fpos = fpos + v.size();  
  41.                         count++;  
  42.                     }  
  43.                     else  
  44.                     {  
  45.                         break;  
  46.                     }  
  47.                 }  
  48.             }  
  49.             cout << str_original << " " << count << endl;  
  50.             count = 0;  
  51.         }  
  52.     }  
  53.     return 0;  
  54. }  

沒有留言:

張貼留言