计算元音、辅音等的程序
#include <ctype.h>
#include <stdio.h>
int main() {
char line[150];
int vowels, consonant, digit, space;
// initialize all variables to 0
vowels = consonant = digit = space = 0;
// get full line of string input
printf("Enter a line of string: ");
fgets(line, sizeof(line), stdin);
// loop through each character of the string
for (int i = 0; line[i] != '\0'; ++i) {
// convert character to lowercase
line[i] = tolower(line[i]);
// check if the character is a vowel
if (line[i] == 'a' || line[i] == 'e' || line[i] == 'i' ||
line[i] == 'o' || line[i] == 'u') {
// increment value of vowels by 1
++vowels;
}
// if it is not a vowel and if it is an alphabet, it is a consonant
else if ((line[i] >= 'a' && line[i] <= 'z')) {
++consonant;
}
// check if the character is a digit
else if (line[i] >= '0' && line[i] <= '9') {
++digit;
}
// check if the character is an empty space
else if (line[i] == ' ') {
++space;
}
}
printf("Vowels: %d", vowels);
printf("\nConsonants: %d", consonant);
printf("\nDigits: %d", digit);
printf("\nWhite spaces: %d", space);
return 0;
}
输出
Enter a line of string: C++ 20 is the latest version of C++ yet. Vowels: 9 Consonants: 16 Digits: 2 White spaces: 8
在这里,用户输入的字符串存储在 line 变量中。
最初,变量 vowel、consonant、digit 和 space 都初始化为 0。
然后,使用 for
循环迭代字符串中的字符。在每次迭代中,我们
- 使用
tolower()
函数将字符转换为小写 - 检查字符是元音、辅音、数字还是空格。假设该字符是辅音。那么,
consonant
变量增加 1。
循环结束后,元音、辅音、数字和空格的数量分别存储在变量 vowel、consonant、digit 和 space 中。
注意: 我们使用了 tolower() 函数来简化我们的程序。要使用此函数,我们需要导入 ctype.h 头文件。