The program to find the number of vowels and consonants present in a String in java is simple. It checks each of the characters in strings and compares it with vowels (i.e. a, e, i, o, u).
When the program finds the character equals to vowel then it increases the vow integer else cons integer increases. And at last, the result is displayed.
You may also take the user input instead of declaring the String in a Program. Following the below to take a user input.
Java Program to Find the Number of Vowels and Consonants 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 | //number of vowels and consonants in a string public class CountVowelConsonants { public static void main(String[] args) { String str = "Learning To Code"; int vow = 0, cons = 0; 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') { ++vow; } else if ((ch >= 'a' && ch <= 'z')) { ++cons; } } System.out.println("Number of Vowels : " + vow); System.out.println("Number of Consonants: " + cons); } } |
Output:
Number of Vowels : 6
Number of Consonants: 8