使用指针在字符串中计算元音和辅音的C程序

编写一个C程序,使用指针和while循环在字符串中计算元音和辅音

  1. 我们将一个字符串赋值给字符指针。
  2. if语句检查是否有任何字符等于a、e、i、o、u。如果为真,元音计数将增加。否则,辅音计数增加。
  3. 最后,本示例打印字符串中的总元音和辅音数。
#include <stdio.h>

int main()
{
    char str[100];
    char *ch;
    int vowCount = 0, consCount = 0;

    printf("Please Enter String to Count Vowels and Consonants\n");
    fgets(str, sizeof str, stdin);

    ch = str;
    
    while(*ch != '\0')
    {
        if(*ch == 'a' || *ch == 'e' || *ch == 'i' || *ch == 'o' || *ch == 'u' ||
		*ch == 'A' || *ch == 'E' || *ch == 'I' || *ch == 'O' || *ch == 'U')  
        {
            vowCount++;
        }
        else
        {
            consCount++;
        }
        ch++;
    }
    
	printf("Total Vowels     = %d\n", vowCount);
    printf("Total Consonants = %d\n", consCount - 1);
}
C program to Count Vowels and Consonants in a String using a Pointer

这个C程序使用指针和for循环来计算字符串中的元音和辅音。上面的示例工作正常。但是,它将空格视为辅音。因此,在本例中,我们使用了另一个条件来检查辅音。  

#include <stdio.h>

int main()
{
    char str[100];
    char *ch;
    int vowCount = 0, consCount = 0;

    printf("Please Enter String\n");
    fgets(str, sizeof str, stdin);
  
    for(ch = str; *ch != '\0'; ch++)
    {
        if(*ch == 'a' || *ch == 'e' || *ch == 'i' || *ch == 'o' || *ch == 'u' ||
		*ch == 'A' || *ch == 'E' || *ch == 'I' || *ch == 'O' || *ch == 'U')  
        {
            vowCount++;
        }
        else if((*ch >= 'a' && *ch <= 'z') || (*ch >= 'A' && *ch <= 'Z'))
        {
            consCount++;
        }
    }
    
	printf("Total Vowels     = %d\n", vowCount);
    printf("Total Consonants = %d\n", consCount);
}
Please Enter String
count vowels and consonants example
Total Vowels     = 11
Total Consonants = 20

在这个使用指针计算字符串中的元音和辅音的示例中,if语句根据ASCII码进行检查。

#include <stdio.h>

int main()
{
    char str[100];
    char *ch;
    int vowCount = 0, consCount = 0;

    printf("Please Enter String\n");
    fgets(str, sizeof str, stdin);
  
    for(ch = str; *ch != '\0'; ch++)
    {
        if(*ch == 65 || *ch == 69 || *ch == 73 || *ch == 79 || *ch == 85 ||
		*ch == 97 || *ch == 101 || *ch == 105 || *ch == 111 || *ch == 117)  
        {
            vowCount++;
        }
        else if((*ch >= 65 && *ch <= 90) || (*ch >= 97 && *ch <= 122))
        {
            consCount++;
        }
    }
    
	printf("Total Vowels     = %d\n", vowCount);
    printf("Total Consonants = %d\n", consCount);
}
Please Enter String
learn c program in this tutorial gateway website
Total Vowels     = 16
Total Consonants = 25