【codewars-2】元音字母的个数

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';});
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值