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!
Create an Account
Sign up to track your progress, earn points, and compete with others. Your solutions will be saved automatically.
Create accountHow 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 Mar 2026
Contest runs March 3 - 31. Complete challenges to climb the leaderboard!
Points are calculated for challenges completed during the contest period.