Java Program to count the total number of vowels and consonants in a string

As we know that, the characters a, e, i, o, u are known as vowels in the English alphabet. Any character other than that is known as the consonant.

Example:

Input:  str = "Java is A programming language!";
Output: Number of vowels: 11
Number of consonants: 15

Approach

Java


public class VowelConCount {
    public static void main(String[] args) {

        // Counter variable to store the count of vowels and consonant
        int vCount = 0, cCount = 0;

        // Declare a string
        String str = "Java is A programming language!";

        // Converting entire string to lower case to reduce the comparisons
        str = str.toLowerCase();

        for (int i = 0; i < str.length(); i++) {
            // 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') {
                vCount++;
            }
            // Checks whether a character is a consonant
            else if (str.charAt(i) >= 'a' && str.charAt(i) <= 'z') {
                cCount++;
            }
        }
        System.out.println("Number of vowels: " + vCount);
        System.out.println("Number of consonants: " + cCount);
    }
}


No comments:

Post a Comment