Say I need to code a program that counts how many consonants are in a word, which is contained in an array called "char word[const]"
I've set up an array that contains all of the consonants in the standard English alphabet in upper and lower case, called "char allConsonants[blah]"
I want to set up a comparison, where if one of the variables in the word array matches any of the characters in the allConsonants array, it'll add one to a counter. Something like:
1 2
if (strcmp(word[0], allConsonants) == 0)
++totalConsonants
But obviously that doesn't work. How would I go about doing this? Thanks in advance!
First of all it is enough to define either upper case consonants or lower case consonants. To determine whether a character is present in a string you can use function std::strchr . For example
1 2 3 4
if ( std::strchr( allConsonants, std::toupper( word[0] ) ) != 0 )
{
std::cout << word[0] << " is a consonant" << std::endl;
}
If you know standard algorithms then you can use std::count_if with a lambda expression to count all consonants in a word.
I'm sure that would work, but it's at a level far above where I'm at. A quick ctrl+f through my textbook shows that lambda expressions and std::strchr functions aren't even covered.