简体   繁体   English

计算每个单词的元音

[英]Count the vowels of every word

I have to count the vowels of evey word in a given text.我必须计算给定文本中每个单词的元音。 My attempt :我的尝试:

#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: I know that my code is a mix between C and C++, but this is what I am taught in school. PS:我知道我的代码是 C 和 C++ 的混合体,但这是我在学校教的。

This is my solution:这是我的解决方案:

#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;
}

If you have a vowel( a, e, i, o or u) you are adding up to the counter.如果你有一个元音(a、e、i、o 或 u),你就会把它加起来。 You can also use strchr but this is a more simple, understandable method.您也可以使用 strchr,但这是一种更简单易懂的方法。

Case closed in the comments.案例在评论中结束。

However, for the fun, I propose you another variant that avoids to use the terrible strtok() , doesn't require a risky strcpy() , and processes each input character only one.但是,为了好玩,我建议您避免使用可怕的strtok()另一种变体,不需要危险的strcpy() ,并且只处理每个输入字符一个。

As you are bound to your teacher's mixed style and apparently are not supposed to use c++ strings yet, I also respected this constraint:由于您受到老师的混合风格的束缚,并且显然不应该使用 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=='\0' || 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; 

Demo演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM