Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Practice › Strings

Count Vowels

Easy · Strings · Asked at TCS, Infosys, Wipro, Accenture, Cognizant

Count the vowels (a e i o u, upper or lower case) in a line of text.

Input

One line of text (may contain spaces, digits and punctuation).

Output

The number of vowels.

Constraints

Read the whole line (getline in C++, nextLine in Java, input() in Python).

Example 1

Input

Hello World

Output

3

Example 2

Input

rhythm

Output

0

Hints

  1. The line can contain spaces, so read the whole line — not just one word.
  2. Lower-case each character and check whether it is one of a, e, i, o, u.

Approach

Read the full line (getline in C++, nextLine in Java, input() in Python). Reading with cin >> s stops at the first space. Convert each character to lower case and count it if it's in "aeiou".

Complexity: O(n) time · O(1) extra space

Solution

C++ solution

#include <bits/stdc++.h>
using namespace std;

int main() {
    string line;
    getline(cin, line);
    int count = 0;
    for (char ch : line) {
        char c = tolower((unsigned char)ch);
        if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') count++;
    }
    cout << count << "\n";
    return 0;
}

Python solution

line = input()
print(sum(1 for ch in line.lower() if ch in "aeiou"))

Java solution

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String line = sc.nextLine().toLowerCase();
        int count = 0;
        for (char c : line.toCharArray())
            if ("aeiou".indexOf(c) >= 0) count++;
        System.out.println(count);
    }
}

Solve Count Vowels online · All practice problems