Start learning free

LESSON 220 OF 291 · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

Count the Vowels in Scala: Looping Over a String

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

    SCALA · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Count The Vowels in Scala, explained

    Problem overview

    The function countVowels takes a string s and returns how many vowels it contains. The vowels are a, e, i, o and u, in lower or upper case. The letter y doesn't count. Consonants, spaces, digits and punctuation are skipped.

    In "Hello World" the vowels are e, o and o, so the answer is 3. In "AlgoCademy" they are A, o, a and e, so the answer is 4: the capital A counts and the y doesn't. In "Why try?" there are none, so the answer is 0.

    Approach

    Look at each character once, ask "is this a vowel?", and keep a counter. The question is the interesting part. Instead of comparing against ten letters with a long chain of conditions, store all the vowels in one string, "aeiouAEIOU", and look the character up in it. Both cases are in the string, so no case conversion is needed.

    Strings have an indexOf method that returns the position of the first match, or -1 when there is none. It accepts a single Char, so vowels.indexOf(c) is -1 exactly when c is not a vowel. For example, "aeiouAEIOU".indexOf('e') is 1, indexOf('A') is 5, and indexOf('y') is -1.

    Step by step

    1. Store the ten vowels in val vowels. It is a val because the set of vowels never changes.
    2. Create var count, starting at 0. It changes inside the loop, so it must be a var.
    3. Write a for loop with a variable c over s. Looping over a String gives each character as a Char.
    4. Inside the loop, if vowels.indexOf(c) is not -1, add 1 to count with count += 1.
    5. After the loop, return count. Returning inside the loop would stop after the first character.

    For "Hello World", the characters that pass the check, and the count after each, are:

    Charactercount after it
    e1
    o2
    o3

    The other characters, H, l, l, the space, W, r, l and d, are not in vowels and change nothing.

    The solution in Scala

    class Solution {
        def countVowels(s: String): Int = {
            val vowels = "aeiouAEIOU"
            var count = 0
            for (c <- s) {
                if (vowels.indexOf(c) != -1) {
                    count += 1
                }
            }
            return count
        }
    }
    

    Details that matter in Scala:

    • for (c <- s) reads "for each c in s". The <- arrow is the generator. A string behaves like a sequence of characters, and c is a Char.
    • != compares values. Here it compares two Int numbers.
    • A character literal uses single quotes, like 'e'. A string of one character uses double quotes. The two are different types, and indexOf is called with a Char in this solution because c is one.
    • Scala has no ++ for numbers, so use count += 1.

    Edge cases and common mistakes

    • Upper-case vowels. With only "aeiou" in vowels, the A of "AlgoCademy" would be missed and the answer would be 3 instead of 4.
    • The letter y. It isn't in vowels, so "Why try?" gives 0.
    • Checking against -1. indexOf returns 0 for the first character of vowels, which is a perfectly good match. A test such as indexOf(c) > 0 would skip every lower-case a.
    • Counting once per character. Each character of s is checked once, so repeated vowels count each time they appear.

    Testing

    countVowels("Hello World") -> 3
    countVowels("AlgoCademy")  -> 4
    countVowels("Why try?")    -> 0
    
    Keep going with Scala1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free