int countConsonant(string str, int consonant)
{
int length = str.length();
consonant = 0;
for (int i = 0; i < length; i++)
{
if(str[i] == 'b'&& str[i] == 'c' && str[i] == 'd'&& str[i] == 'f'
&& str[i] == 'g'&& str[i] == 'h'&& str[i] == 'j' && str[i] == 'k'&& str[i] == 'l'&& str[i] == 'm'
&& str[i] == 'n'&& str[i] == 'p'&& str[i] == 'q'&& str[i] == 'r'&& str[i] == 's'&& str[i] == 't'
&& str[i] == 'v'&& str[i] == 'w'&& str[i] == 'x'&& str[i] == 'y'&& str[i] == 'z')
consonant = consonant + 1;
}
return consonant;
}
int countConsonant(string str, int consonant) { int length = str.length(); consonant = 0; for
Share
You were close, but should check with logical-or
||, not logical-and&&(str[i]simply can’t be equal to two different things).The C++03 Standard allows you to use the keywords
andandor– andnot,xoretc – instead of these cryptic (for new programmers) symbols, but this hasn’t caught on widely – perhaps because Microsoft’s compiler doesn’t default to being Standard-compliant in this regard – presumably to avoid breaking existing client code that has variables, functions, types etc. with these names. So, for portability and simplicity, many libraries and textbooks avoid these keywords too.Another approach that might be a little more concise is to use
isalpha()from<cctype>then check it’s not a vowel. Faster approaches tend to use arrays from character value tobool, but beware indexing outside the array due to signed character values or >=128 bit non-ASCII values. If there’s also uppercase/lowercase to consider – you may want to usetolower()on your character before testing it (i.e.char c = tolower(str[i])); if (c == '...).Other notes: your function should:
std::stringargument byconstreference (i.e.const std::string& str) to avoid unnecessary and time-consuming copying of the value from the calling context into a separate variable local to this function. The copying doesn’t do any real functional harm, but it’s unnecessary.consonanta local variable rather than a function parameter, as any inputted value is immediately clobbered with 0, and the result it returned by the function rather than written intoconsonant(which would be impossible as it is passed by value rather than passed by pointer/reference).