Count Vowels and Consonants in a Line

beginner Strings

Problem

Read one line. Count the vowels (a, e, i, o, u) and the consonants (all other letters). Ignore case, digits, spaces and symbols. Print vowels=<count> consonants=<count>.

Constraints

  • 0 <= length <= 10^5, ASCII

Examples

Input

Hello World

Output

vowels=3 consonants=7

Solutions

Best approachTime O(n)Space O(1)

One loop is enough. We check that a character is a letter, then decide if it is a vowel or a consonant.

Same code works in Java810172125Basic features only, so nothing changes between versions.
/*
 * Problem : Process one line of text.
 * Input   : One line of text.
 * Output  : Vowel and consonant counts.
 * Approach: Count in one loop.
 * Time    : O(n)
 * Space   : O(1)
 * Java    : 8 or newer.
 */
import java.util.Scanner;

public class Main {
    // This method solves the task. It receives the input and returns the answer.
    static String solve(String s) {
        // Step 1: Two counters.
        int vowels = 0;
        int consonants = 0;

        // Step 2: Look at every character in lower case.
        for (char c : s.toLowerCase().toCharArray()) {
            // Step 3: Only letters count.
            if (c >= 'a' && c <= 'z') {
                // Step 4: A vowel is one of a, e, i, o, u. Any other letter is a consonant.
                if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
                    vowels++;
                } else {
                    consonants++;
                }
            }
        }
        return "vowels=" + vowels + " consonants=" + consonants;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String s = scanner.hasNextLine() ? scanner.nextLine() : "";
        System.out.println(solve(s));
    }
}
Hints (1)
  1. Is a digit a consonant?