Description
To count vowels, consonants, digits and whitespaces, check the characters in string is vowel, consonant, digit and whitespaces and increase corresponding count.
C/C++
/* C Program to count Vowels, Consonants, Digits and Whitespaces */ //Save it as CountVowelsConsonantsDigitsWhitespaces.c #include<stdio.h> #include<string.h> int main(){ char str[100]; int i; printf("Enter a string : "); gets(str); int vowel=0, consonant=0, digit=0, whitespace=0; for(i=0;i<strlen(str);i++) { if((str[i]>='a' && str[i]<='z') || (str[i]>='A' && str[i]<='Z')) { if(str[i]=='a' || str[i]=='A' || str[i]=='e' || str[i]=='E' || str[i]=='i' || str[i]=='I' || str[i]=='o' || str[i]=='O' || str[i]=='u' || str[i]=='U'){ vowel++; }else{ consonant++; } }else if(str[i]>='0' && str[i]<='9'){ digit++; }else if(str[i] == ' ') { whitespace++; } } printf("Number of vowel = %d", vowel); printf("\nNumber of consonant = %d", consonant); printf("\nNumber of digit = %d", digit); printf("\nNumber of whitespace = %d", whitespace); return 0; }
Input: Enter a string : pwe arf386q tu Output: Number of vowel = 3 Number of consonant = 6 Number of digit = 3 Number of whitespace = 2
Java
/* Java Program to count Vowels, Consonants, Digits and Whitespaces */ //Save it as CountVowelsConsonantsDigitsWhitespaces.java import java.io.*; import java.util.Scanner; public class CountVowelsConsonantsDigitsWhitespaces { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Enter a string : "); String str = scanner.nextLine(); char newStr[] = str.toCharArray(); int vowel=0, consonant=0, digit=0, whitespace=0; for(int i=0;i<newStr.length;i++) { if((newStr[i]>='a' && newStr[i]<='z') || (newStr[i]>='A' && newStr[i]<='Z')) { if(newStr[i]=='a' || newStr[i]=='A' || newStr[i]=='e' || newStr[i]=='E' || newStr[i]=='i' || newStr[i]=='I' || newStr[i]=='o' || newStr[i]=='O' || newStr[i]=='u' || newStr[i]=='U'){ vowel++; }else{ consonant++; } }else if(newStr[i]>='0' && newStr[i]<='9'){ digit++; }else if(newStr[i] == ' ') { whitespace++; } } System.out.println("Number of vowel = "+ vowel); System.out.println("Number of consonant = "+ consonant); System.out.println("Number of digit = "+ digit); System.out.println("Number of whitespace = "+ whitespace); } }
Input: Enter a string : pwe arf386q tu Output: Number of vowel = 3 Number of consonant = 6 Number of digit = 3 Number of whitespace = 2
Related Programs
1) Program to check entered character is vowel or consonants2) How to find Length or Size of a String
3) Program to Insert a String into Another String
4) Program to check String is Palindrome
5) Program to sort characters of strings in alphabetical order
6) Program to Sort set of strings in alphabetical order
7) Program to find frequency of occurrence of a character
8) Program to remove vowels from a String
9) Program to Replace Spaces With Dots
10) Find Occurrence Of Each Word In a Sentence