In this article, we will write a Java program to count the vowels and consonants in a String.
Program to count 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 converted each char of the string to lowercase using toLowerCase() method for easy comparison.
We are then comparing each char of the string to vowels ‘a’, ‘e’, ‘i’, ‘o’, ‘u’ using charAt() method and if..else..if statement, if a match is found then we are increasing the vowel counter vcount
else we are increasing the Consonant counter ccount
.
public class JavaExample { public static void main(String[] args) { String str = "BeginnersBook"; 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:
Related Java programs
1. Java program to find the occurrence of a character in a String
2. Java program to perform bubble sort on Strings
3. Java program to reverse a String
4. Java program to check vowel or consonant using Switch Case
Leave a Reply