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
Java Strings
Java String Methods
Java StringBuilder and Text Blocks
Exercises & Assignments
Reverse a string
Check if a string is a palindrome
Count the vowels in a string
Interview Questions & Answers
What is the difference between == and equals() in Java?
Why is String immutable in Java?
What is the difference between String, StringBuilder and StringBuffer?
What is the string pool in Java and what does intern() do?