In this example you are going to learn how effectively you can able to write a C program to count the vowels in a String.
This program covers the below concepts:
1. String in C
2. String Array in C
3. Check if a char exists in a String.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
#include <stdio.h> #include <string.h> int main() { int i, j = 0; //declare array values char* vow[] = {"a","e","i","o","u"}; //string char mystring[100]; //capture the string from user printf("Enter the String: "); scanf("%s", mystring); //convert to lowercase, if string entered in CAPS for(i=0;i<=strlen(mystring);i++) { if(mystring[i]>=65&&mystring[i]<=90) mystring[i]=mystring[i]+32; } //loop through 5 vowels for(i=0; i< 5; i++) { //if vowel exists in mystring then add + 1 to j if (strchr(mystring, *vow[i]) != NULL) { j++; } } //print total number of vowels exists in mystring printf("Total Vowels: %d \n", j); return 0; } |
The code is self explanatory, just read the comments in the above program to understand it step by step.
You need to import two packages:
1. stdio.h – Handles input & output operation
2. string.h – Handles String operations
strchr() function helps to check if a character exists in a string. So basically we are looping the vowels one by one and comparing with the entered string (mystring). If any one of the vowel is present in the mystring, then incrementing the value of j by 1 (j++).