Start learning free

LESSON 223 OF 293 · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

Count the Vowels in Rust: Looping Over chars()

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

    RUST · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Count The Vowels in Rust, explained

    Problem overview

    The function count_vowels 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.

    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 upper-case A counts, the y doesn't. "Why try?" has none.

    Approach

    Look at each character once, and add 1 to a counter when it is a vowel. The "is it a vowel" test is a membership question: is this character one of ten known characters? Storing those ten in a string, "aeiouAEIOU", lets you ask the string whether it contains the character.

    Listing both cases is simpler than converting each character to lower case first. It also leaves no doubt about y: it just isn't in the string.

    Step by step

    1. Store the vowels in vowels: "aeiouAEIOU", all ten characters.
    2. Create count at 0. It is mutable because it grows inside the loop.
    3. Loop over s.chars(). A string can't be looped over directly in Rust. chars() produces its characters one at a time.
    4. Test each character. When vowels.contains(c) is true, add 1 to count. Other characters are skipped.
    5. Return count as the last expression, after the loop has seen every character.

    The solution in Rust

    impl Solution {
        fn count_vowels(s: String) -> i32 {
            let vowels = "aeiouAEIOU";
            let mut count = 0;
            for c in s.chars() {
                if vowels.contains(c) {
                    count += 1;
                }
            }
            count
        }
    }
    
    • chars() yields char values. A Rust char is one Unicode character, written with single quotes, as in 'e'. That is different from a one-letter string, which uses double quotes.
    • contains accepts a char. str::contains takes a pattern, and a single char is a valid one. "aeiouAEIOU".contains('e') is true and "aeiouAEIOU".contains('y') is false.
    • vowels is a &str. A string literal is a borrowed slice that lives for the whole program, so a plain let is enough.
    • Counter type. count starts as a bare 0 and Rust makes it an i32, because the function returns i32.
    • Why not index the string? Strings in Rust are UTF-8 bytes, so s[i] isn't allowed. chars() walks the characters correctly, and it is the usual way to visit each one.

    Edge cases and common mistakes

    • Upper case. "AEIOU aeiou" gives 10: all ten letters count, and the space doesn't.
    • No vowels. "Sky" and "Why try?" give 0, since y is not a vowel here.
    • Forgetting one case. A vowels string with only lower-case letters would miss the A in "AlgoCademy" and return 3.
    • Passing the wrong type. The loop variable c is a char, so it goes to contains as it is. A String or a number would not be the right kind of pattern.
    • Using the byte length. s.len() counts bytes. For this lesson's ASCII text it equals the number of characters, but s.chars().count() is the way to count characters in general.
    • Counting letters, not occurrences. Each vowel counts every time it appears, so "Hello World" counts the two o's separately.

    Testing

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