Java Program to Count Vowels and Consonants in a String
To count vowels and consonants in a String, iterate over each character of the string and check if the character is vowel or consonant. If the character is vowel, increment vowel count, or if the character is consonant, increment consonant count.
In this tutorial, we shall write Java program to count number of vowels and consonants in a string.
Count Vowels and Consonants in String using For Loop
Algorithm
We shall use the following algorithm to write Java program for counting vowels and consonants in the string.
- Start.
- Read input string to a variable
str
, or initialize the variable with a string constant. - Transform input string to lower case and replace any character other than alphabet with an empty string. Store the resulting string in
alpha
. - Initialize
vowels
with 0 andconsonants
with 0. These are the counters for vowels and consonants respectively in the string. - For each character in alpha, check if the character is vowel. If true, increment vowels, else increment consonants.
vowels
has the count for number of vowels in the string, andconsonants
have the count for number of consonants in the string.- Stop.
Java Program
</>
Copy
/**
* Java Program - Count Vowels and Consonants
*/
public class CountVowelConsonant {
public static void main(String[] args) {
String str = "apple is fruit.";
String alpha = str.toLowerCase().replaceAll("[^a-z]", "");
int vowels = 0;
int consonants = 0;
for (char ch: alpha.toCharArray()) {
if(ch == 'a' || ch=='e' || ch == 'i' || ch=='o' || ch == 'u')
vowels++;
else
consonants++;
}
System.out.println("Vowels : "+vowels);
System.out.println("Consonants : "+consonants);
}
}
Output
Vowels : 5
Consonants : 7
Conclusion
In this Java Tutorial, we learned how to count vowels and consonants in a given string.