如何用 C 语言计算字符串中元音和辅音的数量?
cserver side programmingprogramming更新于 2025/5/15 21:52:17
问题
如何编写 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 程序 −
/* 计算字符串中的元音和辅音 */ #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