如何用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\n : "); 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\n", vowels); printf("consonants in this String = %d", consonants); return 0; }输出结果
执行以上程序后,将产生以下结果-
Enter any String: TutoriasPoint vowels in this String = 6 consonants in this String = 7