Given a string, count the number of vowels and consonants and return them in a Map with two keys: vowels and consonants. A vowel is one of a, e, i, o, u (case insensitive). A consonant is any other letter of the English alphabet. Non-letter characters such as digits, spaces, and punctuation are ignored. Return null when the input is null. Return a map with both counts set to zero when the input is an empty string.

Examples:

Input: str = 'Hello World' Output: { vowels => 3, consonants => 7 } Explanation: Vowels are e, o, o. Consonants are H, l, l, W, r, l, d. Input: str = 'aeiou' Output: { vowels => 5, consonants => 0 } Explanation: All characters are vowels. Input: str = 'rhythm' Output: { vowels => 0, consonants => 6 } Explanation: y is not counted as a vowel here. Input: str = 'Apex 123!' Output: { vowels => 2, consonants => 2 } Explanation: Digits and punctuation are ignored. Input: str = null Output: null Explanation: Null input returns null.
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.

Wally can't hear you

Please sign in to access the AI Assistant

Sign In