Skip to content

Latest commit

 

History

History
66 lines (49 loc) · 2.08 KB

File metadata and controls

66 lines (49 loc) · 2.08 KB

C 程序:计算元音,辅音等的数量

原文: https://www.programiz.com/c-programming/examples/vowel-consonant-frequency-string

在此示例中,对用户输入的字符串中的元音,辅音,数字和空格进行计数。

要理解此示例,您应该了解以下 C 编程主题:


计算元音,辅音等的程序

#include <stdio.h>
int main() {
    char line[150];
    int vowels, consonant, digit, space;

    vowels = consonant = digit = space = 0;

    printf("Enter a line of string: ");
    fgets(line, sizeof(line), stdin);

    for (int i = 0; line[i] != '\0'; ++i) {
        if (line[i] == 'a' || line[i] == 'e' || line[i] == 'i' ||
            line[i] == 'o' || line[i] == 'u' || line[i] == 'A' ||
            line[i] == 'E' || line[i] == 'I' || line[i] == 'O' ||
            line[i] == 'U') {
            ++vowels;
        } else if ((line[i] >= 'a' && line[i] <= 'z') || (line[i] >= 'A' && line[i] <= 'Z')) {
            ++consonant;
        } else if (line[i] >= '0' && line[i] <= '9') {
            ++digit;
        } 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: adfslkj34 34lkj343 34lk
Vowels: 1
Consonants: 11
Digits: 9
White spaces: 2 

在此,用户输入的字符串存储在line变量中。

首先,将变量vowelsconsonantdigitspace初始化为 0。

然后,使用for循环迭代字符串的字符。 在每次迭代中,都会检查字符是否为元音,辅音,数字和空格。 假设字符是元音,在这种情况下,vowel变量增加 1。

循环结束时,元音,辅音,数字和空格的数量分别存储在变量vowelsconsonantdigitspace