c++ - 计算字符串中元音的个数

标签 c++ algorithm

我编写了一个程序来计算字符串中的元音数量,但它的代码效率不高或没有优化。 此外,它不会检查大写元音。

#include<iostream.h>
using namespace std;
int main()
{
unsigned int vow_cnt=0;
char name[15]= "sijith aeu";
cout<<"Enter a name"<<endl;
cin>>name;
for(unsigned int i=0;i<strlen(name);i++)
{ 
  if(name[i] == 'a' || name[i] == 'e'||name[i] == 'i'||name[i] == 'o'||name[i] == 'u')
  { 
   vow_cnt++;
  }
 }
cout<<"vow_cnt"<< vow_cnt << endl;
}

最佳答案

考虑到您假设只有 e i o u 是元音字母并且您的字符串全部为小写,请尝试以下操作: 当然,这在 unicode 或具有不同元音集的每种语言中都会严重失败。

bool is_vowel(char x) {
  // order by probability of occurrence in the target language
  // e.g. start with e for English
  // nb see comments for further details
  return (x == 'e' || ...); 
}

std::string foo;
long nbVowels = std::count_if(foo.begin(), foo.end(), is_vowel);

关于c++ - 计算字符串中元音的个数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7429309/

相关文章:

r - 精确存储大整数

algorithm - 按比例平衡 3 个值

c++ - QQuickView 和 QQuickWindow 有什么区别?

android - 手机摄像头是否有可能以不规则的 fps 拍摄视频?

c++ - 从 std::bitset::operator[] 推导模板

java - 需要设计帮助/建议

python - 2个函数的时空复杂度

algorithm - O(log log N) 复杂度循环是怎样的?

c++ - 为什么 gcc 即使被要求也不提示数组边界?

c++ - While循环与for循环中的迭代器失效