C语言计算元音、辅音等的数量的程序

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


计算元音、辅音等的程序

#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 变量中。

最初,变量 vowelconsonantdigitspace 都初始化为 0

然后,使用 for 循环迭代字符串中的字符。在每次迭代中,我们

  • 使用 tolower() 函数将字符转换为小写
  • 检查字符是元音、辅音、数字还是空格。假设该字符是辅音。那么,consonant 变量增加 1

循环结束后,元音、辅音、数字和空格的数量分别存储在变量 vowelconsonantdigitspace 中。

注意: 我们使用了 tolower() 函数来简化我们的程序。要使用此函数,我们需要导入 ctype.h 头文件。

在我们结束之前,让我们来检验一下你对这个例子的理解!你能解决下面的挑战吗?

挑战

编写一个函数,从给定字符串中返回前 N 个元音字母。

  • 从输入字符串中返回前 N 个元音字母。
  • 假设:字符串的大小永远不会超过 100 个字符。
  • 例如,对于输入 str = "Hello World"N = 3,返回值应为 "eoo"
你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战