Start learning free

LESSON 216 OF 667 · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

Count the Vowels in C++: A Range-Based for Loop and find

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

    C++ · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Count The Vowels in C++, explained

    Problem overview

    The function 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 is not a vowel here, and every other character (consonants, spaces, digits, punctuation) is skipped.

    For "Hello World" the answer is 3: the vowels are e, o and o. For "AlgoCademy" it is 4: A, o, a and e, because the upper-case A counts and the y doesn't. For "Why try?" it is 0.

    Approach

    The function looks at each character once and asks one question: is it one of the ten vowel characters? To keep that question short, it stores the ten vowels in a string, "aeiouAEIOU", and asks whether the character occurs in it. Storing both cases means the function doesn't have to convert anything to lower case first.

    The question is answered with find. vowels.find(c) searches the string vowels for the character c and returns its position, or the special constant string::npos when it isn't there. So c is a vowel exactly when the result is not string::npos.

    Here is the loop on "Hello World", one character at a time:

    'H' skip count=0
    'e' vowel count=1
    'l' skip count=1
    'l' skip count=1
    'o' vowel count=2
    ' ' skip count=2
    'W' skip count=2
    'o' vowel count=3
    'r' skip count=3
    'l' skip count=3
    'd' skip count=3
    

    The space is checked like any other character and is simply not found in vowels.

    Step by step

    1. Store the vowels. Create a string named vowels holding "aeiouAEIOU". The letter y is left out on purpose.
    2. Create count as an int starting at 0. No character has been checked yet.
    3. Visit every character. A range-based for loop with a char variable c over s works, because a string is a sequence of chars.
    4. Test and count. Inside the loop, if vowels.find(c) != string::npos, add 1 to count with ++. Characters that aren't in vowels do nothing.
    5. Return count after the loop, not inside it, so that every character is checked first.

    The solution in C++

    class Solution {
    public:
        int countVowels(string s) {
            string vowels = "aeiouAEIOU";
            int count = 0;
            for (char c : s) {
                if (vowels.find(c) != string::npos) {
                    count++;
                }
            }
            return count;
        }
    };
    

    The C++ details:

    • Range-based for. for (char c : s) gives c a copy of each character in turn, from the first to the last. There is no index to manage and no risk of going out of bounds.
    • string::find has several overloads. It accepts a string or a single char. With a char it returns the position of its first occurrence as a size_t, an unsigned type, or string::npos, which is the largest value of that type. That is why the comparison uses npos by name and not a number such as -1 or 0: position 0 is a valid result, the first a in vowels.
    • The return value of find is not a boolean. Writing if (vowels.find(c)) would be false only for a, which is at position 0, and true for every other character, including those that were not found.
    • The string is copied. The parameter is passed by value. For long strings, a const string& parameter avoids the copy, but the lesson keeps the signature simple.

    Why a string of vowels

    The test could also be written as ten comparisons joined with ||: c == 'a' || c == 'e' || .... That is long and easy to get wrong, for example by forgetting one upper-case letter. A string of vowels keeps the list of vowels in one place, and the loop body stays one line long whatever the list contains. Changing which letters count is then a change to one string, not to the logic.

    An alternative: convert to lower case

    Another way is to store only "aeiou" and lower-case each character with tolower before searching. That is shorter to store, but each character needs a conversion, and tolower takes and returns an int, so the result needs a cast back to char for find to pick the single-character overload. On "AlgoCademy" this version also counts 4. Keeping both cases in one string avoids the conversion and the cast.

    Complexity

    Time: O(n) for a string of n characters. Each character costs one search of a ten-character string, which is a constant amount of work. Space: O(1) beyond the copy of the input.

    Edge cases and common mistakes

    • Upper case. "AEIOUaeiou" returns 10. If only the lower-case vowels were stored, the upper-case ones would be missed.
    • The letter y. "Why try?" returns 0, and so does "xyz".
    • Non-letters. Spaces, digits and punctuation are never in vowels, so they are skipped without special handling.
    • Returning inside the loop. A return count; inside the loop body would end the function after the first character.
    • Repeated vowels. Every occurrence counts, even when two vowels are side by side or the same letter repeats, so "AEIOUaeiou" returns 10 and not 5.

    Testing

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