字数统计程序

编程入门 行业动态 更新时间:2024-10-21 20:32:08
本文介绍了字数统计程序-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.

更多推荐

字数统计程序

本文发布于:2023-11-11 07:08:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1577725.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字数   程序

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!