Last Updated: 26 Nov, 2020

Count Consonants In A String

Easy
Asked in companies
OptumFarEye

Problem statement

Given a string ‘STR’ which consists of uppercase and lowercase characters and spaces. Count the number of consonants in the string.

A consonant is an English alphabet character that is not vowel (a, e, i, o, and u). Examples of constants are b, c, d, f, etc.

Example :

Given string 'STR' : ‘Coding Ninjas’ there are 8 consonants i.e ‘C’,’d’,’n’,’g’,’N’,’n’,’j’,’s’, because these characters do not belong to set above mentioned set of vowels.
Input Format :
The first line of input contains an integer ‘T’ denoting the number of test cases.
The next ‘T’ lines represent the ‘T’ test cases.

The only line of each test case consists of a string ‘STR’
Output Format :
For each test case, print a single integer denoting the number of consonants in the string.
Note :
You don't need to print anything, it has already been taken care of. Just implement the given function.
Constraints :
1 <= T <= 50
1 <= Length of 'STR' <= 10^4

The string consists of uppercase and lowercase characters and spaces.

Time Limit: 1 sec

Approaches

01 Approach

If we can find if the current character is a consonant or not we can create a recursive to count all the vowels.

 

  1. Let ‘i’ be the index of the current character we are at and ‘N’ be the length of the string.
  2. Then for every character ‘i’ we check if it is a consonant or not(a character is a consonant if it is not A, E, I, O, U), If it is we add 1 and call the function recursively to find the answer for the next ‘N - i’ characters.
  3. In the base case, when we reach the last character we return 1 if it is a consonant else we return 0
  4. Finally, we return the answer once we have checked all the characters.

02 Approach

We can simply check if every element is a consonant or not and keep the count of the number of consonants using a simple for loop.

 

Here is the algorithm :

 

  1. Create a variable (say, ‘COUNT’) to store the number of consonants.
  2. Create an iterator (say, ‘i’) such that for every index ‘i’ check if ‘STR’[i] is a consonant or not((a character is a consonant if it is not A, E, I, O, U).
  3. If it is a consonant increment the ‘COUNT’ variable.
  4. Finally, return ‘COUNT’.