Count the vowels in a string

Description: Count how many vowels (a, e, i, o, u) and how many consonants are in "Learn Java Programming".

Hint:

  • Use toCharArray(), Character.isLetter() and indexOf on the string "aeiou".

Solution

public class Main {
    public static void main(String[] args) {
        String text = "Learn Java Programming";
        int vowels = 0, consonants = 0;

        for (char c : text.toLowerCase().toCharArray()) {
            if (!Character.isLetter(c)) continue;          // skip the spaces
            if ("aeiou".indexOf(c) >= 0) {
                vowels++;
            } else {
                consonants++;
            }
        }
        System.out.println("Vowels: " + vowels + ", consonants: " + consonants);
    }
}
Output

Vowels: 7, consonants: 13

How it works

  • "aeiou".indexOf(c) gives -1 when the letter is not a vowel.
  • continue skips the spaces.

Read Java String Methods.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.