how to sort the duplicated alphabet into one,AA=A only?

/*******************************************************************************

Your Task:
Write a program that accepts a word as an input, and outputs
the number of different consonants (b,d,f,g,h...) in the word.
The word consists of small and capital alphabets only.

For example, the output for the word "Lolz" is 2 because
there are 2 different consonants ('l' and 'z')

Sample run 1 :
Enter a word -> Lolz
Number of different consonants : 2

Sample run 2 :
Enter a word -> MamMaMia
Number of different consonants : 1

*******************************************************************************/

#include <iostream>
#include <string>
#include <cctype>
using namespace std;

int main()
{
char cons;
int consonantCount = 0;
string word;

cout << "Please enter a word which consists only small and capital alphabets. " << endl;
getline(cin, word);

for ( int pos = 0; pos < word.length(); pos++)
{
cons = toupper (word[pos]);
switch(cons)
{ case 'B' :
case 'C' :
case 'D' :
case 'F' :
case 'G' :
case 'H' :
case 'J' :
case 'K' :
case 'L' :
case 'M' :
case 'N' :
case 'P' :
case 'Q' :
case 'R' :
case 'S' :
case 'T' :
case 'V' :
case 'W' :
case 'X' :
case 'Y' :
case 'Z' : consonantCount++;
}
}
cout << "Number of different consonant= " << consonantCount << endl;
system ("pause");
return 0;
}

// End Question
A simple way is to maintain a 'visited' array.
So you just increment the counter if it was not visited already.
You could populate a set and print the size of the set:

1
2
3
4
5
    std::set<char> unique_consonants;
    for(size_t pos = 0; pos < word.length(); ++pos)
        if(isConsonant(word[pos]))
            unique_consonants.insert( std::tolower(word[pos]) );
    std::cout << "Number of different consonant= " << unique_consonants.size() << '\n';

online demo: http://ideone.com/V44zA
I think that 'Y' is not a consonant.

So you will have 19 consonants.

You can use a constant string with 19 consonants and std::bitset<19> for your program. Something as

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const size_t N = 19;
const std::string consonants( "BCDFGHKLMNPQRSTVWXZ" );
std::bitset<N> accumulator;
std::string word;

std::cout << "Enter a word: ";
std::cin >> word;

for ( auto it = word.begin(); it != word.end(); ++it )
{
	std::string::size_type pos = consonants.find( std::toupper( *it ) );
	if ( pos != std::string::npos ) accumulator.set( pos );
}

std::cout << "Number of consonants: "
	<< accumulator.count() << std::endl;


Example of the output:

Enter a word: This
Number of consonants: 3
Last edited on
Topic archived. No new replies allowed.