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