[英]word length statistic C language
誰能幫我做那個項目。
編寫一個程序,計算一個句子的單詞長度統計信息。 該句子以“。”開頭。 對於找到的每個單詞長度,將打印該長度的單詞數。 僅打印在輸入中找到的那些長度。 只允許來自z或AZ的字母組成單詞。 單詞之間用空格隔開。 除“。”外,沒有標點符號。 被允許。 如果識別出任何其他輸入字符或輸入長度超過80個字符,程序將顯示“ NOT VALID”(無效)(請參閱提示)。 請注意,在輸入中沒有單詞的情況下,不會打印任何內容。
% u6_stats
Enter a sentence: Bolt was expected to use the super bark.
Length 2: 1
Length 3: 3
Length 4: 2
Length 5: 1
Length 8: 1
% u6_stats
Enter a sentence: Something wasn’t right.
NOT VALID
#include <stdio.h>
#include <conio.h>
void main() {
char s[100];
int numOfWords, lengthOfWord = 0;
int i = 0, j = 0;
printf("Enter the text : ");
fgets(s, sizeof(s), stdin);
numOfWords = 1;
while(s[i]!='\0') {
if(s[i] == ' ')
numOfWords++;
i++;
}
//printf("%d", numOfWords);
i = 0;
int help[numOfWords];
int l;
for(l = 0; l < numOfWords ; l++)
help[l] = 0;
while(s[i]!='\0') {
if(s[i] != ' ' && s[i] !='\n' && s[i]!='.' ) {
lengthOfWord++;
i++;
}else{
help[j] = lengthOfWord;
j++;
lengthOfWord = 0;
i++;
}
}
int repeat[80];
for(l = 0; l < 80 ; l++)
repeat[l] = 1;
int num = 1;
i=0,l=0;
for(i = 0;i<numOfWords;i++) {
for(l=i+1;l<numOfWords;l++)
if(help[i]==help[l]) {
repeat[l]='\0';
num++;
repeat[i] = num;
}
num = 1;
}
l=0;
for (l=0; l<numOfWords; l++)
if (repeat[l]!='\0' && help[--l]!=help[++l])
printf("Length %d: %d\n", help[l],repeat[l]);
}
因此,問題是,如果我輸入“ abc abcd abc abc”之類的文本,結果將類似於“長度3:3長度4:1長度3:2”。 因此,當程序已經將第一個(此處為3個)元素與其他元素進行了比較時,該元素將不再進行比較,但是我具有相同長度的3d元素,在這種情況下,程序會將其與其余元素進行比較並打印2。如果我不比較已比較的元素,我可以重做我的代碼嗎?
第二個問題是我需要從最小長度到最大長度得到結果。
一種簡單的方法是使用strtok( http://www.tutorialspoint.com/c_standard_library/c_function_strtok.htm )。
#include <stdio.h>
int numwords (char *str);
int main() {
char word[] = "This is a test - does it pass?";
int c = numwords(word);
printf("Words = %d\n", c);
return 0;
}
int numwords(char *str)
{
int n = 0;
for(str=strtok(str, " -.!,;"); str; str=strtok(NULL, " -.!,;"))
n++;
return n;
}
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
void invalid(void){
puts("NOT VALID");
exit(EXIT_FAILURE);
}
int main(void){
int length[80]={0};
int i, ch, word_len=0;
printf("Enter a sentence: ");
while(1){
ch=getchar();
if(isalpha(ch)){
++word_len;
} else if(ch == ' ' || ch == '.'){
if(word_len>80)
invalid();
if(word_len)
length[word_len-1]++;//-1: to 0 origin
if(ch == '.')
break;
word_len = 0;
} else {
invalid();
}
}
for(i=0;i<sizeof(length)/sizeof(*length);++i){
if(length[i])
printf("Length %d: %d\n", i+1, length[i]);
}
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.