Learner Level

Implement the method countConsonants that returns the number of consonants in a string.

Count consonant letters in a string. Vowels are a, e, i, o, and u, in either lowercase or uppercase form.

The task is designed to test careful handling of edge cases, not only the most common input.

  • Ignore digits, spaces, and punctuation.
  • Count both uppercase and lowercase consonants.
  • Return 0 when no consonant exists.
Example 1
Input:
s (string) = hello
Return:
(int) 3
Example 2
Input:
s (string) = AEIOU
Return:
(int) 0
Example 3
Input:
s (string) = W3Schools
Return:
(int) 6
Example 4
Input:
s (string) = sky
Return:
(int) 3

For each character, first check whether it is alphabetic. If it is a letter and not a vowel, increase the count.

Run your code to see the result.