我想知道我是否可以尋求一些幫助。我正在用C編寫一個程序,寫出字符,單詞和元音的數量在字符串中(帶有幾個添加的打印語句)。我想弄清楚如何編寫一個循環遍歷字符串的代碼,並計算至少包含3個元音的單詞的數量。我覺得這是一個非常簡單的代碼,但它總是最難忘的東西。任何幫助?如何統計包含至少3個元音的字數
另外:作爲新的C,我怎麼能得到相同的結果,而使用功能int vowel_count(char my_sen[])
,而不是使用中我主要的代碼?
如果這是一個有點混亂我的意思是因爲我的主已經包含代碼來計算我的輸入元音的數量,我怎麼能稍微轉移到這個函數的代碼,仍然在主要調用它?
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define SENTENCE 256
int main(void){
char my_sen[SENTENCE], *s; //String that containts at most 256 as well as a pointer
int words = 1, count = 0,vowel_word = 0; //Integer variables being defined
int i,vowel = 0, length; //More definitions
printf("Enter a sentence: ");//Input sentence
gets(my_sen);//Receives and processes input
length = strlen(my_sen); //Stores the length of the input within length
for(i=0;my_sen[i] != '\0'; i++){
if(my_sen[i]=='a' || my_sen[i]=='e' || my_sen[i]=='i' || my_sen[i]=='o' || my_sen[i]=='u' || //Loop that states if the input contains any of the following
my_sen[i]=='A' || my_sen[i]=='E' || my_sen[i]=='I' || my_sen[i]=='O' || my_sen[i]=='U') //characters(in this case, vowels), then it shall be
{ //stored to be later printed
vowel++;
}
if(my_sen[i]==' ' || my_sen[i]=='!' || my_sen[i]=='.' || my_sen[i]==',' || my_sen[i]==';' || //Similar to the vowel loop, but this time
my_sen[i]=='?') //if the following characters are scanned within the input
{ //then the length of the characters within the input is
length--; //subtracted
}
}
for(s = my_sen; *s != '\0'; s++){ //Loop that stores the number of words typed after
if(*s == ' '){ //each following space
count++;
}
}
printf("The sentence entered is %u characters long.\n", length); //Simply prints the number of characters within the input
printf("Number of words in the sentence: %d\n", count + 1); // Adding 1 to t[he count to keep track of the last word
printf("Average length of a word in the input: %d\n", length/count);//Prints the average length of words in the input
printf("Total Number of Vowels: %d\n", vowel);//Prints the number of vowels in the input
printf("Average number of vowels: %d\n", vowel/count);//Prints the average number of vowels within the input
printf("Number of words that contain at least 3 vowels: %d\n", vowel_word);//Prints number of words that contain at least 3 vowels
return 0;
}
如果您創建了類似於'type *'函數的函數來檢查元音,那麼第一個'if'語句中的條件可能會更具可讀性。第二個if語句也是如此 –