In this simple Java program, learn to find the count of vowels and consonants in a given input string.
1. How to count vowels and consonants in a String
In English alphabets, there are 5 vowels (‘a’, ‘e’, ‘i’, ‘o’ and ‘u’) and rest are consonants.
Please keep in mind that a string in java can have several kind of characters such as :
- alphabets
- numbers
- special characters
- white spaces etc.
We have to find and count the alphabets in such a way that we can filter out other kind of characters.
Algorithm
Follow given algorithm to count the vowels and consonants separately.
- Read an input string
- Convert the string to lower case so that comparisons can be reduced
- Iterate over it’s characters one by one
- If current character matches with vowels (a, e, i, o, u ) then increment the vCount by 1
- Else if any character lies between ‘a’ and ‘z’, then increment the count for cCount by 1
- Print both the counts
2. Java program to count vowels and consonants in String
package com.howtodoinjava.example; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Input string : "); // 1 String str = scanner.nextLine(); scanner.close(); // 2 str = str.toLowerCase(); int vCount = 0, cCount = 0; //3 for (int i = 0; i < str.length(); i++) { //4. Checks whether a character is a vowel if (str.charAt(i) == 'a' || str.charAt(i) == 'e' || str.charAt(i) == 'i' || str.charAt(i) == 'o' || str.charAt(i) == 'u') { // Increments the vowel counter vCount++; } //5. Checks whether a character is a consonant else if (str.charAt(i) >= 'a' && str.charAt(i) <= 'z') { // Increments the consonant counter cCount++; } } //6 System.out.println("Number of vowels: " + vCount); System.out.println("Number of consonants: " + cCount); } }
Program output.
Input string : how to do in java Number of vowels: 6 Number of consonants: 7
Drop me your questions related to program to count the number of vowels and consonants in a given string in Java.
Happy Learning !!