Count Vowels and Consonants in String
Count the number of vowels and consonants in a given string. Return a Map with keys 'vowels' and 'consonants' containing the respective counts. Only count alphabetic characters (a-z, A-Z). Ignore spaces, numbers, and special characters.
Method Signature
public static Map<String, Integer> countVowelsConsonants(String str)
Examples
Example 1:
Input: "Hello World"
Output: {"vowels" => 3, "consonants" => 7}
Explanation: Vowels are 'e', 'o', 'o' (3 total). Consonants are 'H', 'l', 'l', 'W', 'r', 'l', 'd' (7 total).
Example 2:
Input: "AEIOU"
Output: {"vowels" => 5, "consonants" => 0}
Explanation: All characters are vowels.
Example 3:
Input: "xyz123"
Output: {"vowels" => 0, "consonants" => 3}
Explanation: Only 'x', 'y', 'z' are consonants. The numbers '123' are ignored.
Example 4:
Input: null Output: null Explanation: Return null for null input.
Apex Code Editor
Welcome to Lightning Challenge!
How It Works
- • Write your solution in the code editor
- • Connect your Salesforce org to test
- • Submit to check if your solution passes
- • Use hints if you get stuck
Contest Alert
🏆 #CodeEveryDay July 2026
Contest runs July 1 - 31. Complete challenges to climb the leaderboard!
Only the 31 daily challenges shown during this contest count toward points. Earlier dailies don't carry over.