Count the vowels (a, e, i, o, u) and consonants in a string, ignoring digits and symbols.
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).
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, cA simple classification/counting exercise that checks clean iteration and membership tests — the same pattern as categorizing any stream of items.
The string contains digits and punctuation. Should they count as consonants?