← Back to libraryQuestion 61 of 273
⌨️Java CodingBeginner

Count Vowels and Consonants

📌 Definition:

Count the vowels (a, e, i, o, u) and consonants in a string, ignoring digits and symbols.

📖 Detailed Explanation:

Lowercase the string, then for each alphabetic character increment the vowel counter if it is in the vowel set, else the consonant counter. Non-letters are skipped. O(n).

💻 Solutions:
public static int[] countVowelsConsonants(String s) {
    int v = 0, c = 0;
    for (char ch : s.toLowerCase().toCharArray()) {
        if (!Character.isLetter(ch)) continue;
        if ("aeiou".indexOf(ch) >= 0) v++; else c++;
    }
    return new int[]{v, c};
}
function countVowelsConsonants(s) {
  let v = 0, c = 0;
  for (const ch of s.toLowerCase()) {
    if (!/[a-z]/.test(ch)) continue;
    if ('aeiou'.includes(ch)) v++; else c++;
  }
  return { vowels: v, consonants: c };
}
def count_vowels_consonants(s):
    vowels = set('aeiou')
    v = sum(1 for ch in s.lower() if ch in vowels)
    c = sum(1 for ch in s.lower() if ch.isalpha() and ch not in vowels)
    return v, c
🔑 Key Points:
  • Lowercase first for case-insensitivity
  • Only count alphabetic characters
  • Use a set/membership test for vowels
  • O(n) single pass
🌍 Real-World Example:

A simple classification/counting exercise that checks clean iteration and membership tests — the same pattern as categorizing any stream of items.

🎯 Scenario-Based Interview Question:

The string contains digits and punctuation. Should they count as consonants?