C++ Program to Find the Number of Vowels, Consonants, Digits and White Spaces in a String


A string is a one dimensional character array that is terminated by a null character. There can be many vowels, consonants, digits and white spaces in a string.

For example.

String: There are 7 colours in the rainbow
Vowels: 12
Consonants: 15
Digits: 1
White spaces: 6

A program to find the number of vowels, consonants, digits and white spaces in a string is given as follows.

Example

 Live Demo

#include <iostream>
using namespace std;
int main() {
   char str[] = {"Abracadabra 123"};
   int vowels, consonants, digits, spaces;
   vowels = consonants = digits = spaces = 0;
   for(int i = 0; str[i]!='\0'; ++i) {
      if(str[i]=='a' || str[i]=='e' || str[i]=='i' ||
      str[i]=='o' || str[i]=='u' || str[i]=='A' ||
      str[i]=='E' || str[i]=='I' || str[i]=='O' ||
      str[i]=='U') {
         ++vowels;
      } else if((str[i]>='a'&& str[i]<='z') || (str[i]>='A'&& str[i]<='Z')) {
         ++consonants;
      } else if(str[i]>='0' && str[i]<='9') {
         ++digits;
      } else if (str[i]==' ') {
         ++spaces;
      }  
   }
   cout << "The string is: " << str << endl;
   cout << "Vowels: " << vowels << endl;
   cout << "Consonants: " << consonants << endl;
   cout << "Digits: " << digits << endl;
   cout << "White spaces: " << spaces << endl;
   return 0;
}

Output

The string is: Abracadabra 123
Vowels: 5
Consonants: 6
Digits: 3
White spaces: 1

In the above program, the variables vowels, consonants, digits and spaces are used to store the number of vowels, consonants, digits and spaces in the string. A for loop is used to examine each character of a string. If that character is a vowels, then vowels variable is incremented by 1. Same for consonants, digits and spaces. The code snippet that demonstrates this is as follows.

for(int i = 0; str[i]!='\0'; ++i) {
if(str[i]=='a' || str[i]=='e' || str[i]=='i' ||
str[i]=='o' || str[i]=='u' || str[i]=='A' ||
str[i]=='E' || str[i]=='I' || str[i]=='O' ||
str[i]=='U') {
   ++vowels;
   } else if((str[i]>='a'&& str[i]<='z') || (str[i]>='A'&& str[i]<='Z')) {
      ++consonants;
   } else if(str[i]>='0' && str[i]<='9') {
      ++digits;
   } else if (str[i]==' ') {
      ++spaces;
   }
}

After the occurrences of the vowels, consonants, digits and spaces in the string are calculated, they are displayed. This is shown in the following code snippet.

The string is: Abracadabra 123
Vowels: 5
Consonants: 6
Digits: 3
White spaces: 1

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 24-Jun-2020

894 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements