gpt4 book ai didi

c - 字数统计程序 - stdin

转载 作者:太空宇宙 更新时间:2023-11-04 01:22:03 24 4
gpt4 key购买 nike

下面为question ,

Write a program to read English text to end-of-data (type control-D to indicate end of data at a terminal, see below for detecting it), and print a count of word lengths, i.e. the total number of words of length 1 which occurred, the number of length 2, and so on.

Define a word to be a sequence of alphabetic characters. You should allow for word lengths up to 25 letters.

Typical output should be like this:

        length 1 : 10 occurrences
length 2 : 19 occurrences
length 3 : 127 occurrences
length 4 : 0 occurrences
length 5 : 18 occurrences
....

To read characters to end of data see above question.


这是我的工作解决方案,

#include<stdio.h>
int main(void){
char ch;
short wordCount[20] = {0};
int count = 0;
while(ch = getchar(), ch >= 0){
if(ch == ' ' || ch == ',' || ch == ';'|| ch == ':'|| ch == '.'|| ch == '/'){
wordCount[count]++;
count=0;
}else{
count++;
}
}
wordCount[count]++; // Incrementing here looks weird to me

for(short i=1; i< sizeof(wordCount)/sizeof(short); i++){
printf("\nlength %d : %d occurences",i, wordCount[i]);
}
}

问题:

1)

从代码优雅的角度来看,我可以避免在 while 循环之外递增 (++) wordCount 吗?

2)

我能否根据单词大小使 wordCount 数组大小更加动态,而不是恒定大小 20

注意:了解了 struct 但还没有学习动态结构,例如 Linkedlist

最佳答案

对于动态分配,您可以从 20 个 shorts 的空间开始(尽管问题陈述似乎要求您允许最多 25 个字符的单词):

short maxWord = 20;
short *wordCount = malloc(sizeof(*wordCount) * maxWord);

然后,当您增加 count 时,如果当前单词的长度超过动态数组中可以计算的长度,您可以分配更多空间:

} else {
count++;
if (count >= maxWord) {
maxWord++;
wordCount = realloc(sizeof(*wordCount) * maxWord);
}
}

完成后不要忘记 free(wordCount)

由于您不需要计算零长度单词,您可以考虑修改您的代码,以便 wordCount[0] 存储长度为 1 的单词数,依此类推。

关于c - 字数统计程序 - stdin,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40015903/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com