📌  相关文章
📜  用来计算字符串中元音和辅音数量的C程序

📅  最后修改于: 2021-05-25 21:36:43             🧑  作者: Mango

给定一个字符串,并编写一个C程序来计算该字符串中元音和辅音的数量。

例子:

Input: str = "geeks for geeks"
Output:
Vowels: 5
Consonants: 8

Input: str = "abcdefghijklmnopqrstuvwxyz"
Output:
Vowels: 5
Consonants: 21

方法:

  • 以字符串作为输入
  • 从该字符串取出每个字符以进行检查
  • 如果此字符是元音,请增加元音的数量
  • 否则增加辅音的数量。
  • 最后打印元音和辅音的总数。

下面是上述方法的实现:

// C program to count the number of
// vowels and consonants in a string
  
#include 
  
// Function to count number
// of vowels and consonant
void count_vowels_and_consonant(char* str)
{
    // Declare the variable vowels and consonant
    int vowels = 0, consonants = 0;
  
    int i;
    char ch;
  
    // Take each character from this string to check
    for (i = 0; str[i] != '\0'; i++) {
  
        ch = str[i];
  
        // If this character is a vowel,
        // increment the count of vowels
        if (ch == 'a' || ch == 'e'
            || ch == 'i' || ch == 'o'
            || ch == 'u' || ch == 'A'
            || ch == 'E' || ch == 'I'
            || ch == 'O' || ch == 'U')
            vowels++;
  
        // If this character is a space
        // skip it
        else if (ch == ' ')
            continue;
  
        else
            // Else increment the count of consonants
            consonants++;
    }
  
    // Print the total count of vowels and consonants
    printf("\nVowels: %d", vowels);
    printf("\nConsonants: %d", consonants);
}
  
// Driver function.
int main()
{
    char* str = "geeks for geeks";
    printf("String: %s", str);
  
    count_vowels_and_consonant(str);
  
    return 0;
}
输出:
String: geeks for geeks
Vowels: 5
Consonants: 8
想要从精选的最佳视频中学习和练习问题,请查看《基础知识到高级C的C基础课程》。