C++中字串子音計數(迭代和遞迴方法)


給定一個字串,例如長度任意的str,任務是使用迭代和遞迴方法計算給定字串中子音的個數。

子音是指不是母音的字母,即除了a、i、e、o、u之外的字母都被認為是子音。所以在下面的程式中,我們需要找到字串中除了這些字母以外的字母個數。

遞迴和迭代都重複執行指令集。遞迴是指函式中的語句重複呼叫自身。迭代是指迴圈重複執行,直到控制條件變為假。遞迴和迭代的主要區別在於,遞迴是一個過程,總是應用於函式,而迭代則應用於我們想要重複執行的指令集。

例如

Input − string str = “tutorials point”
Output − count is 8

說明 − 在給定的字串str中,共有8個子音字母,它們是t、t、r、l、s、p、n和t。

Input − string str = “a e io u”
Output − count is 0

說明 − 在給定的字串str中,沒有子音字母,只有母音字母,所以個數為0。

迭代

下面程式中使用的方法如下

  • 將字串輸入到變數中,例如str

  • 使用length()函式計算給定字串的長度,該函式將根據字串中的字元數返回一個整數值

  • 取一個臨時變數來儲存元素的計數。

  • 從i=0開始迴圈,直到i小於字串的長度

  • 在迴圈內,檢查IF str[i]是子音,則將計數的值加1

  • 返回計數

  • 列印結果。

示例

 線上演示

// Iterative CPP program
#include <iostream>
using namespace std;
// Function to check for consonant
bool consonant(char ch){
   // To handle lower case
   ch = toupper(ch);
   return !(ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') && ch >= 65 && ch <= 90;
}
//function to count consonant
int countconsonants(string s){
   int result = 0;
   for (int i = 0; i < s.length(); i++){
      // To check is character is Consonant
      if (consonant(s[i])){
         ++result;
      }
   }
   return result;
}
// main function
int main(){
   string s = "wx abc def";
   cout <<"count is: "<<countconsonants(s);
   return 0;
}

輸出

如果我們執行上面的程式碼,我們將得到以下輸出

count is: 6

遞迴

下面程式中使用的方法如下

  • 將字串輸入到變數中,例如str

  • 使用length()函式計算給定字串的長度,該函式將根據字串中的字元數返回一個整數值

  • 取一個臨時變數來儲存元素的計數。

  • 建立一個遞迴函式,它將呼叫自身來計算字串中的子音。

  • 檢查IF大小為1,則返回str[0]。

  • 然後,返回recursive_call_to_function為(str, size-1) + 檢查字元是否為字串(str[size-1])

示例

 線上演示

// Recursive CPP program
#include <iostream>
using namespace std;
// Function to check for consonant
bool consonant(char ch){
   // To convert the lower case
   ch = toupper(ch);
   return !(ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') && ch >= 65 && ch <= 90;
}
// to count total number of consonants
int consonantcount(string str, int n){
   if (n == 1){
      return consonant(str[0]);
   }
   return consonantcount(str, n - 1) +
   consonant(str[n-1]);
}
int main(){
   string str = "wx abc def";
   cout <<"count is: "<<consonantcount(str, str.length());
   return 0;
}

輸出

如果我們執行上面的程式碼,我們將得到以下輸出:

count is: 6

更新於:2020年5月15日

619 次瀏覽

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告