Start learning free

LESSON 217 OF 671 · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

Count the Vowels in Java: Looping Over a String's Characters

Practice Read the full explanation

Given a string s, return how many vowels it has.

The vowels are a, e, i, o and u, in lower case or in upper case. The letter y is not a vowel here. Every other character (consonants, spaces, digits, punctuation) is skipped.

 

Example 1:

Input: s = "Hello World"
Output: 3
Explanation: The vowels are e, o and o. The other characters, the space included, are skipped.

Example 2:

Input: s = "AlgoCademy"
Output: 4
Explanation: A, o, a and e are vowels: the upper-case A counts too. The y doesn't count.

Example 3:

Input: s = "Why try?"
Output: 0
Explanation: y is not a vowel, so this string has none.

 

Constraints:

  • s has at least one character and doesn't start or end with a space.
  • s contains English letters, digits, spaces and punctuation.
STEP 1 OF 5
    Ctrl + Enter to check

    JAVA · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Count The Vowels in Java, explained

    Problem overview

    The method countVowels receives a string s and returns how many vowels it has. The vowels are a, e, i, o and u, in lower or upper case. The letter y doesn't count, and neither do consonants, spaces, digits or punctuation.

    "Hello World" has 3 vowels (e, o, o). "AlgoCademy" has 4: A, o, a and e. "Why try?" has none.

    Approach: check each character against a string of vowels

    Visit every character once, and for each decide whether it is a vowel. The simplest test is to keep all ten vowels, both cases, in one string and ask that string where the character appears. Listing both cases in the string avoids converting the input to lower case.

    Step by step

    1. Store the vowels in a String named vowels: "aeiouAEIOU".
    2. Create count as an int starting at 0.
    3. Loop over the characters. An enhanced for loop can't take a String directly, so s.toCharArray() turns it into a char[] first, and the loop variable c is a char.
    4. Test the character. vowels.indexOf(c) returns the position of c in vowels, or -1 when it isn't there. Any result other than -1 means c is a vowel, so add 1 to count.
    5. Return count after the loop, so every character has been checked.

    The solution in Java

    class Solution {
        public int countVowels(String s) {
            String vowels = "aeiouAEIOU";
            int count = 0;
            for (char c : s.toCharArray()) {
                if (vowels.indexOf(c) != -1) {
                    count++;
                }
            }
            return count;
        }
    }
    

    Java details:

    • char versus String. A char is a single character written in single quotes, such as 'e'. A String is written in double quotes. indexOf accepts a char, which is what the loop provides.
    • Which position indexOf returns. "aeiouAEIOU".indexOf('E') is 6 and "aeiouAEIOU".indexOf('y') is -1. The exact position doesn't matter here, only whether it is -1.
    • Case matters. indexOf compares characters exactly, so 'A' would not be found in a string holding only lower-case vowels.
    • Compare with !=. This compares two int values, so it's the right operator. The equals advice for strings doesn't apply.

    Another way to test a character

    Instead of a string of ten vowels, the code can lower-case each character with Character.toLowerCase(c) and compare it to the five lower-case vowels, for example in a switch with case 'a', 'e', 'i', 'o', 'u'. It gives the same counts: 3, 4 and 0 for the three examples above. The string version keeps the test to one short line and puts the list of vowels in one place, where it is easy to read and change.

    Following "Hello World"

    The loop looks at the characters in order. H, l, l, the space, W, r, l and d are not in vowels, so indexOf gives -1 and nothing changes. The vowels raise count to 1 at e, to 2 at the first o and to 3 at the second o. The method returns 3. Note that "aeiouAEIOU".indexOf('a') is 0, so the first vowel in the string passes the test != -1, while 'H' gives -1.

    Edge cases and common mistakes

    • Upper-case vowels. Leaving them out of vowels would give 3 instead of 4 for "AlgoCademy".
    • The letter y. It stays out of the string, so "Why try?" gives 0.
    • Comparing with > 0. vowels.indexOf(c) > 0 misses the vowel 'a', which sits at position 0.
    • Returning inside the loop. The method would stop after the first character.
    • Non-letters. Spaces, digits and punctuation aren't in vowels, so they get -1 and are skipped without extra code.

    Testing

    • "Hello World" gives 3.
    • "AlgoCademy" gives 4.
    • "Why try?" gives 0.
    Keep going with Java650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free