Using Java
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);
}
}