Exercise:
Write a C++ program that can find white spaces, digits, consonants, and vowels in a string.
Program 1: With C String
Click Here to View Solution:
#include <iostream>
using namespace std;
int main()
{
char words[100];
int cons=0, vow=0, dig=0, spc=0;
cout << "Insert any sentence: ";
cin.getline(words, 100);
for(int i = 0; words[i]!='\0'; ++i)
{
if(words[i]=='a' || words[i]=='e' || words[i]=='i' || words[i]=='o' || words[i]=='u'
|| words[i]=='A' ||words[i]=='E' || words[i]=='I' || words[i]=='O' ||words[i]=='U')
{
++vow;
}
else if (words[i]==' ')
{
++spc;
}
else if((words[i]>='a'&& words[i]<='z') || (words[i]>='A'&& words[i]<='Z'))
{
++cons;
}
else if(words[i]>='0' && words[i]<='9')
{
++dig;
}
}
cout << "\nvowels: " << vow << endl;
cout << "consonants: " << cons << endl;
cout << "blank space: " << spc << endl;
cout << "digits: " << dig << endl;
return 0;
}
Click Here to View Output:
Insert any sentence: the answer to everything is 42 vowels: 8 consonants: 15 blank space: 5 digits: 2
Click Here to View Explanation:
- This code works similar to the frequency check code. The user is requested to enter a sentence.
- 1 by 1, each element of the string is assessed.
If... else
statements are used to check if the entered character is a vowel, capital or small.- Else, it could be a consonant, digit, or a space.
- If present,
vow
,cons
,dig
,spc
is incremented by 1 and then displayed on the screen.
Program 2: With String Object
Click Here to View Solution:
#include <iostream>
using namespace std;
int main()
{
string words;
int cons=0, vow=0, dig=0, spc=0;
cout << "Insert any sentence: ";
getline(cin , words); // string object
for(int i = 0; words[i]!='\0'; ++i)
{
if(words[i]=='a' || words[i]=='e' || words[i]=='i' || words[i]=='o' || words[i]=='u'
|| words[i]=='A' ||words[i]=='E' || words[i]=='I' || words[i]=='O' ||words[i]=='U')
{
++vow;
}
else if (words[i]==' ')
{
++spc;
}
else if((words[i]>='a'&& words[i]<='z') || (words[i]>='A'&& words[i]<='Z'))
{
++cons;
}
else if(words[i]>='0' && words[i]<='9')
{
++dig;
}
}
cout << "\nvowels: " << vow << endl;
cout << "consonants: " << cons << endl;
cout << "blank space: " << spc << endl;
cout << "digits: " << dig << endl;
return 0;
}
Click Here to View Output:
Insert any sentence: the answer to everything is 42 vowels: 8 consonants: 15 blank space: 5 digits: 2
Click Here to View Explanation:
- This code is similar to the code above.
- The only difference is that this code takes a
string object
from the user. The previous code accepts aC Style String
.