如何使用 C 語言計算字串中母音和子音的數量?
問題
如何編寫一個 C 程式來計算給定字串中的母音和子音數量?
解決方案
我們將編寫的查詢母音和子音的實現程式碼的邏輯為 -
if(str[i] == 'A' || str[i] == 'E' || str[i] == 'I' || str[i] == 'O' || str[i] == 'U'||str[i] == 'a' || str[i] == 'e' || str[i] == 'i' || str[i] == 'o' || str[i] == 'u' )
如果此條件得到滿足, 我們嘗試增加母音數量. 否則, 我們會增加子音數量.
示例
以下是用於計算字串中母音和子音數量的 C 程式 -
/* Counting Vowels and Consonants in a String */
#include <stdio.h>
int main(){
char str[100];
int i, vowels, consonants;
i = vowels = consonants = 0;
printf("Enter any String
: ");
gets(str);
while (str[i] != '\0'){
if(str[i] == 'A' || str[i] == 'E' || str[i] == 'I' || str[i] == 'O' || str[i] == 'U'||str[i] == 'a' || str[i] == 'e' || str[i] == 'i' || str[i] == 'o' || str[i] == 'u' ){
vowels++;
}
else
consonants++;
i++;
}
printf("vowels in this String = %d
", vowels);
printf("consonants in this String = %d", consonants);
return 0;
}輸出
當執行以上程式時, 產生了以下結果 -
Enter any String: TutoriasPoint vowels in this String = 6 consonants in this String = 7
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP