不计算字符串中元音的数量

Sij*_*ith 0 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;
}
Run Code Online (Sandbox Code Playgroud)

pmr*_*pmr 5

考虑到你假设只有元音是元音并且你的字符串都是小写的,试试这个:当然,这会在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);
Run Code Online (Sandbox Code Playgroud)