Search⌘ K

Count Consonants in String

Explore how to count consonants in a string by applying both iterative and recursive techniques. Learn to differentiate vowels from consonants and handle special cases like spaces and punctuation. This lesson helps you understand string manipulation with recursion and iteration while considering time complexity for efficient solutions.

We'll cover the following...

In this lesson, we focus on the following problem:

Given a string, calculate the number of consonants present.

The vowels are the following letters:

a e i o u

Any other letter that is not a vowel is a consonant.

Let’s have a look at an example:

Welcome to Educative!

has 9 consonants.

Before you dive into the implementation, consider the edge cases such as spaces and exclamation marks. This implies that if a character is not a vowel, it has to be a letter to be considered a consonant.

Iterative Approach

Check out the iterative approach in the snippet below:

Python 3.5
vowels = "aeiou"
def iterative_count_consonants(input_str):
consonant_count = 0
for i in range(len(input_str)):
if input_str[i].lower() not in vowels and input_str[i].isalpha():
consonant_count += 1
return consonant_count

On line 1, we define vowels globally to be "aeiou". input_str is the given string passed to iterative_count_consonants function which we have to process to calculate the number of consonants. consonant_count is initialized to 0 on line 4 and then the input_str is traversed character by character using a for loop on ...