簡體   English   中英

計算每個單詞的元音

[英]Count the vowels of every word

我必須計算給定文本中每個單詞的元音。 我的嘗試:

#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++ 的混合體,但這是我在學校教的。

這是我的解決方案:

#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,但這是一種更簡單易懂的方法。

案例在評論中結束。

但是,為了好玩,我建議您避免使用可怕的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=='\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; 

演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM