Dear readers today we read in article a Java program to count the vowels and consonants in a String.
The program of counting the vowels and consonants in a given string
Here we have two variables vcount and ccount to keep the count of vowels and consonants respectively. We have changed each chart of the string to the lower part using the toLowerCase () method for easy comparison.
We then compare each chart of the string to the vowels ‘a’, ‘e’, ’i’, ‘o’, ‘u’ using the charAt () method and if..else..if statement, if A match is found then we are increasing the vowel counter vcount, otherwise we are increasing the consonant counter count.
public class JavaExample { public static void main(String[] args) { String str = "fastreadjiqa"; int vcount = 0, ccount = 0; //converting all the chars to lowercase str = str.toLowerCase(); for(int i = 0; i < str.length(); i++) { char ch = str.charAt(i); if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') { vcount++; } else if((ch >= 'a'&& ch <= 'z')) { ccount++; } } System.out.println("Number of Vowels: " + vcount); System.out.println("Number of Consonants: " + ccount); } }
Output:
Number of Vowels: 5 Number of Consonants: 7
Another Example
Java Program to Count the Number of Vowels and Consonants in a Sentence
Program to count vowels, consonants, digits, and spaces
Public class Main { public static void main(String[] args) { String line = "This website is aw3som3."; int vowels = 0, consonants = 0, digits = 0, spaces = 0; line = line.toLowerCase(); for (int i = 0; i < line.length(); ++i) { char ch = line.charAt(i); // check if character is any of a, e, i, o, u if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') { ++vowels; } // check if character is in between a to z else if ((ch >= 'a' && ch <= 'z')) { ++consonants; } // check if character is in between 0 to 9 else if (ch >= '0' && ch <= '9') { ++digits; } // check if character is a white space else if (ch == ' ') { ++spaces; } } System.out.println("Vowels: " + vowels); System.out.println("Consonants: " + consonants); System.out.println("Digits: " + digits); System.out.println("White spaces: " + spaces); } }
Output
Vowels: 7 Consonants: 11 Digits: 2 White spaces: 3