Start learning free

LESSON 219 OF 289 · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

Count the Vowels in C#: foreach 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

    C# · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Count The Vowels in C#, explained

    Problem overview

    CountVowels receives a string s and returns how many vowels it has. The vowels are a, e, i, o and u, in lower case or upper case. The letter y does not count, and every other character (consonants, spaces, digits, punctuation) is skipped.

    "Hello World" has 3 vowels: e, o and o. "AlgoCademy" has 4: A, o, a and e. "Why try?" has none, because y is not a vowel here.

    Approach

    Look at each character once, and add 1 to a counter whenever the character is a vowel. The question "is this character a vowel?" is answered by keeping all ten vowels, both cases, in one string and asking whether the character appears in it. Listing both cases means you don't have to convert the character to lower case first.

    Step by step

    1. Store the vowels in a string named vowels: "aeiouAEIOU". The letter y is not in it.
    2. Create count as an int set to 0. No vowel has been found yet.
    3. Write a foreach loop with a char c over s. A string can be looped over directly, and each item is a char.
    4. Test vowels.Contains(c) and add 1 to count with ++ when it is true. Characters that aren't vowels are simply not counted.
    5. Return count after the loop, not inside it, so that every character is checked first.

    Here is "AlgoCademy", character by character:

    cIn vowels?count
    Ayes1
    lno1
    gno1
    oyes2
    Cno2
    ayes3
    dno3
    eyes4
    mno4
    yno4

    The solution in C#

    class Solution {
        public int CountVowels(string s) {
            string vowels = "aeiouAEIOU";
            int count = 0;
            foreach (char c in s) {
                if (vowels.Contains(c)) {
                    count++;
                }
            }
            return count;
        }
    }

    string.Contains has a version that takes a single char, so vowels.Contains(c) compiles with the char from the loop. It also has a version that takes a string, so "abc".Contains("bc") is true as well. Both return a bool, and the comparison is case-sensitive, which is why the upper-case vowels are listed.

    The loop variable c of a foreach is read-only: you can use it but not assign to it. Strings are immutable in C#, so the loop only reads the string and never changes it.

    Other ways to test a vowel

    The ten-letter string is easy to read and easy to extend. Two other common choices are lower-casing each character with char.ToLower(c) and checking it against "aeiou", or a switch with one case per vowel. They give the same counts. The string version keeps the rule in one place: to change which letters count, you change one string and nothing else.

    Each lookup scans at most ten characters, so the cost per character is a small constant, and the whole method takes time in proportion to the length of s.

    Edge cases and common mistakes

    • Upper-case vowels. Without AEIOU in vowels, the A in "AlgoCademy" would be missed and the answer would be 3 instead of 4.
    • The letter y. It is not in the string, so "Why try?" gives 0.
    • Returning too early. A return inside the loop would end the method at the first character.
    • Repeated vowels. Every vowel counts each time it appears: "queue" has 4.
    • Non-letters. Spaces, digits and punctuation are never in vowels, so they are skipped without any special code.

    Testing

    The solution returns 3 for "Hello World", 4 for "AlgoCademy", 0 for "Why try?" and 4 for "queue".

    Keep going with C#1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free