数每个单词的元音

Count the vowels of every word

本文关键字:单词      更新时间:2023-10-16

我必须计算给定文本中 evey 单词的元音。我的尝试 :

#include <iostream>
#include <string.h>
using namespace std;
char s[255], *p, x[50][30];
int c;
int main()
{
cin.get(s, 255);
cin.get();
p = strtok(s, "?.,;");
int n = 0;
while (p)
{
n++;
strcpy(x[n], p);
p = strtok(NULL, "?.,;");
}
for (int i = 1; i <= n; i++)
{
c = 0;
for (int j = 0; j < strlen(x[i]); j++)
if (strchr("aeiouAEIOU", x[i][j]))
c++;
cout << c << " ";
}
return 0;
}

PS:我知道我的代码是C和C++的混合,但这是我在学校学到的。

案例在注释中关闭。

然而,为了好玩,我向你推荐了另一种变体,避免使用可怕的strtok(),不需要有风险的strcpy(),并且每个输入字符只处理一个。

由于您受老师的混合风格的约束,并且显然还不应该使用 c++ 字符串,因此我也尊重此约束:

const char separators[]=" t?.,;:"; // I could put them in the code directly
const char vowels[]="aeiouyAEIOUY"; //    but it's for easy maintenance
int vowel_count=0, word_count=0;
bool new_word=true; 
char *p=s;
cout << "Vowels in each word: ";
do  {
if (*p=='' || strchr(separators,*p)) {
if (!new_word) {   // here, we've reached the end of a word
word_count++; 
cout << vowel_count << " ";
vowel_count = 0; 
new_word=true; 
}                 // else it's still a new word since consecutive separators
} 
else {               // here we are processing real chars of a word
new_word=false;   // we have at least on char in our word
if (strchr(vowels, *p))
vowel_count++;
}
} while (*p++);  // It's a do-while so not to repeat the printing at exit of loop
cout << endl<<"Words: "<<word_count<<endl; 

演示

这是我的解决方案:

#include <iostream>
#include <string.h>
using namespace std;
int main()
{
char s[255];
int n,i,counter=0;
cin.get(s,255);
for(i=0; i<=strlen(s)-1; i++)
if(s[i]=='a' || s[i]=='e' || s[i]=='i' || s[i]=='o' || s[i]=='u') counter++;
cout<<counter;
return 0;
}

如果你有一个元音(a,e,i,o或u(,你正在加到计数器。 您也可以使用 strchr,但这是一种更简单、更易于理解的方法。