C++ Program to Count Number of Vowels, Consonant, and Spaces in String

C++ program to find number of Vowel, Consonant, Digits and Spaces in a String.


C++ Program to count various characters using functions

#include<iostream>

using namespace std;
 
int isVowel(char c);
int isConsonant(char c);
int isDigit(char c);
int isWhitespace(char c);
 
int main(){
    char str[500];
    int V = 0, C = 0, D = 0, W = 0, i;
    
    cout << "Enter a string\n";
    gets(str);
    
 for(i = 0;str[i] != '\0'; i++) {
  if(isVowel(str[i])){
   V++;
  } else if(isConsonant(str[i])) {
   C++;
  } else if (isDigit(str[i])){
   D++;
  } else if (isWhitespace(str[i])){
   W++;
  }
    }
    
    cout << "Vowels: "<<V<<endl;
    cout << "Consonants: "<<C<<endl;
    cout << "Digits: "<<D<<endl;
    cout << "White spaces: "<<W<<endl;
    
    return 0;
}
 
int isVowel(char c){
 if(c=='a'||c=='e'||c=='i'||c=='o'||c=='u'||c=='A'||c=='E'||c=='I'||c=='O'||c=='U'){ 
     return 1;
 } else {
     return 0;
 }
}
 
int isConsonant(char c) {
 if(((c>='a'&& c<='z') || (c>='A'&& c<='Z')) && !isVowel(c)){
  return 1;
 } else {
  return 0;
 }
}
 
int isDigit(char c) {
 if(c>='0'&&c<='9'){
  return 1;
 } else {
  return 0;
 }
}
 
int isWhitespace(char c) {
 if(c == ' '){
  return 1;
 } else {
  return 0;
 }
}

Output
Enter a string
tech crash course 1234
Vowels: 5
Consonants: 10 
Digits: 4
White spaces: 3

Recommended Posts
C++ Program to Find the Frequency of Characters in a String
C++ Program to find length of string
C++ Program to concatenate two strings without using strcat function.
C++ Program to Copy String Without Using strcpy
C++ Program to Find Smallest Element in Array
C++ Program to Find Largest Element of an Array
C++ Program to Check Whether a Character is Vowel or Consonant
C++ Program to Delete Spaces from String or Sentence
C++ Program to Delete Vowels Characters from String
C++ Program to Count Words in Sentence
C++ Program to Delete a Word from Sentence
All C++ Programs