用 C++ 統計給定字串中母音字母對的數量
給定一個字元字串,任務是計算其中母音字母對的數量。我們知道英語字母表中有五個母音字母:a、i、e、o、u,其他字元稱為子音字母。
輸入 − 字串 str = "tutorials point"
輸出 − 給定字串中母音字母對的數量為:2
解釋 − 從給定的字串中,我們可以形成以下對:(t, u), (u, t), (t, o), (o, r), (r, i), (i, a), (a, l), (l, s), (s, p), (p, o), (o, i), (i, n) 和 (n , t)。因此,兩個元素都是母音字母的對是 (i, a) 和 (o, i),所以母音字母對的數量是 2。
輸入 − 字串 str = "learning"
輸出 − 給定字串中母音字母對的數量為:1
輸入 − 從給定的字串中,我們可以形成以下對:(l, e), (e, a), (a, r), (r, n), (n, i), (i, n) 和 (n, g)。因此,只有一對兩個元素都是母音字母:(e, a),所以母音字母對的數量是 1。
下面程式中使用的演算法如下
將字元字串輸入到字串型別的變數中
使用 length() 函式計算字串的長度,該函式將返回字串中字元的總數
使用一個臨時變數 count 來儲存母音字母對的數量。
從 i = 0 開始迴圈,直到字串的長度
在迴圈內,檢查 IF str[i] 是 ‘a’ OR ‘i’ OR ‘e’ OR ‘o’ OR ‘u’,然後檢查 IF str[i+1] 是 ‘a’ OR ‘i’ OR ‘e’ OR ‘o’ OR ‘u’,如果是,則將 count 的值加 1
返回 count
列印結果
示例
#include <bits/stdc++.h>
using namespace std;
int count_pairs(string str, int length){
int count = 0;
for(int i=0 ;i<length-1; i++){
if(str[i]=='a' || str[i]=='i'||str[i]=='e'||str[i]=='o'||str[i]=='u'){
if(str[i+1]=='a'||str[i+1]=='i'||str[i+1]=='e'||str[i+1]=='o'||str[i+1]=='u'){
count++;
}
}
}
return count;
}
int main(){
string str = "tutorials point";
int length = str.length();
cout<<"Count the pairs of vowels in the given string are: "<<count_pairs(str, length);
return 0;
}輸出
如果我們執行上面的程式碼,它將生成以下輸出:
Count the pairs of vowels in the given string are: 2
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP