字数统计程序-STDIN [英] Word count program - stdin
问题描述
对于以下问题,>
编写一个程序以读取英语文本到数据结尾(类型为control-D的数字表示终端的数据结尾,请参见下文进行检测),并打印一个字长计数,即出现的长度为1的单词,长度为2的数量,等等.
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.
将一个单词定义为字母字符序列.您应该允许最多25个字母的单词长度.
Define a word to be a sequence of alphabetic characters. You should allow for word lengths up to 25 letters.
典型输出应如下所示:
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.
这是我的工作解决方案,
Here is my working solution,
#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
吗?
From code elegance aspect, Can I avoid incrementing(++) wordCount
outside while
loop?
2)
我可以根据字长而不是恒定大小 20
来使 wordCount
数组大小更动态吗?
Can I make wordCount
array size more dynamic based on word size, rather than constant size 20
?
注意:了解 struct
,但尚未学习动态结构,例如 Linkedlist
Note: Learnt about struct
but am yet to learn dynamic structures like Linkedlist
推荐答案
对于动态分配,您可以以20个 shorts
的空格开头(尽管问题陈述似乎要求您允许单词最多25个字符):
For the dynamic allocations you can start with space for 20 shorts
(although the problem statement appears to ask for you to allow for words up to 25 characters):
short maxWord = 20;
short *wordCount = malloc(sizeof(*wordCount) * maxWord);
然后,当当前单词的长度大于动态数组中可以计数的长度时,当增加 count
时,您可以分配更多空间:
Then, when you increment count
you can allocate more space if the current word is longer than can be counted in your dynamic array:
} else {
count++;
if (count >= maxWord) {
maxWord++;
wordCount = realloc(sizeof(*wordCount) * maxWord);
}
}
完成后别忘了 free(wordCount)
.
由于不需要计算零个长度的单词,因此您可以考虑修改代码,以便 wordCount [0]
存储长度为1的单词数,依此类推.
Since you don't need to count zero-length words, you might consider modifying your code so that wordCount[0]
stores the number of words of length 1, and so on.
这篇关于字数统计程序-STDIN的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!