Algorithm
1. Start
2. Declare variables for vowels, consonants, digits, and white spaces, initialized to 0.
3. Input a string from the user.
4. Loop through each character in the string:
a. Check if the character is a vowel (a, e, i, o, u or their uppercase versions).
- If true, increment the vowel count.
b. Check if the character is a consonant (alphabet character that is not a vowel).
- If true, increment the consonant count.
c. Check if the character is a digit (0-9).
- If true, increment the digit count.
d. Check if the character is a white space (space, tab, newline, etc.).
- If true, increment the white space count.
5. Display the counts of vowels, consonants, digits, and white spaces.
6. En
Code Examples
#1 Code Example- C++ programing From a C-style string
Code -
C++ Programming
#include <iostream>
using namespace std;
int main()
{
char line[150];
int vowels, consonants, digits, spaces;
vowels = consonants = digits = spaces = 0;
cout << "Enter a line of string: ";
cin.getline(line, 150);
for(int i = 0; line[i]!='\0'; ++i)
{
if(line[i]=='a' || line[i]=='e' || line[i]=='i' ||
line[i]=='o' || line[i]=='u' || line[i]=='A' ||
line[i]=='E' || line[i]=='I' || line[i]=='O' ||
line[i]=='U')
{
++vowels;
}
else if((line[i]>='a'&& line[i]<='z') || (line[i]>='A'&& line[i]<='Z'))
{
++consonants;
}
else if(line[i]>='0' && line[i]<='9')
{
++digits;
}
else if (line[i]==' ')
{
++spaces;
}
}
cout << "Vowels: " << vowels << endl;
cout << "Consonants: " << consonants << endl;
cout << "Digits: " << digits << endl;
cout << "White spaces: " << spaces << endl;
return 0;
}
Copy The Code &
Try With Live Editor
Output
Vowels: 7
Consonants: 10
Digits: 1
White spaces: 6
#2 Code Example- C++ Programing From a String Object
Code -
C++ Programming
#include <iostream>
using namespace std;
int main()
{
string line;
int vowels, consonants, digits, spaces;
vowels = consonants = digits = spaces = 0;
cout << "Enter a line of string: ";
getline(cin, line);
for(int i = 0; i < line.length(); ++i)
{
if(line[i]=='a' || line[i]=='e' || line[i]=='i' ||
line[i]=='o' || line[i]=='u' || line[i]=='A' ||
line[i]=='E' || line[i]=='I' || line[i]=='O' ||
line[i]=='U')
{
++vowels;
}
else if((line[i]>='a'&& line[i]<='z') || (line[i]>='A'&& line[i]<='Z'))
{
++consonants;
}
else if(line[i]>='0' && line[i]<='9')
{
++digits;
}
else if (line[i]==' ')
{
++spaces;
}
}
cout << "Vowels: " << vowels << endl;
cout << "Consonants: " << consonants << endl;
cout << "Digits: " << digits << endl;
cout << "White spaces: " << spaces << endl;
return 0;
}
Copy The Code &
Try With Live Editor
Output
Vowels: 8
Consonants: 14
Digits: 1
White spaces: 5
Demonstration
C++ Programing Example to Find the Number of Vowels, Consonants, Digits and White Spaces in a String-DevsEnv