Return the number (count) of vowels in the given string.
返回给定字符中元音字母的个数。
We will consider a, e, i, o, u as vowels for this Kata (but not y).
aeiou作为元音字母。
The input string will only consist of lower case letters and/or spaces.
输入字符串仅由小写字母和空格组成。
要点
- 要用
size_t
类型的整数和字符长度进行比较
#include <string>
bool is_vowel(char ch ){
switch(ch){
case 'a' :
case 'e':
case 'i':
case 'o':
case 'u':
return true;
break;
default:
return false;
}
return false ;
}
int getCount(const string& inputStr){
int num_vowels = 0;
for(size_t i = 0 ; i< inputStr.length() ; ++i){
if( is_vowel(inputStr[i]) ) ++num_vowels ;
}
return num_vowels;
}
更好的题解
- 使用
std::count_if
: 即只要条件满足就计数+1. 返回值为计数总数. - 这种临时的判断元音函数写成lambda表达式的形式
#include <string>
int getCount(const std::string& str)
{
return std::count_if(str.begin(), str.end(), [](int i){return i == 'a' || i == 'e' || i == 'i' || i == 'o'|| i == 'u';});
}