如何使用 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