深圳集团网站开发网站开发公司,用wordpress做博客,wordpress模板+免费,网络系统管理学什么Last One ! 文章目录 1109 综合实验#xff1a;文件操作与字符处理总结 1109 综合实验#xff1a;文件操作与字符处理
时间限制:4000MS 代码长度限制:10KB 提交次数:6265 通过次数:1646
题型: 填空题 语言: GCC Description 在当前目录中存在文件名为case1.in文件操作与字符处理总结 1109 综合实验文件操作与字符处理
时间限制:4000MS 代码长度限制:10KB 提交次数:6265 通过次数:1646
题型: 填空题 语言: GCC Description 在当前目录中存在文件名为case1.in其中case后为数字1不是字母l写错提交后会判错的文本文件 其内容为一篇英文文章以EOF作为结束标志。现要求读取该文本文件内容统计文章中每个单词出现的次数 并输出出现次数最多的前5个单词及其出现次数按出现次数由多到少的顺序输出次数相同时按字典顺序输出 不足5个单词时按序输出全部单词。程序中注意如下细节 1 空格、标点符号与回车符起到分隔单词的作用。 2 文章一行的末尾可能有连字符出现连字符时该行最末的字符串与下行最先出现的字符串构一个单词 3 名词缩写算一个单词 4 数字不算单词 5 单词不区分大小写 6 输出时单词全使用小写
#include stdio.h
#include math.h
#include string.h
#include stdlib.h_______________________main()
{_______________________
}输入格式 文件case1.in中一篇英文文章包含多段文字单词数不超过10000每个单词不超过20个字符
输出格式 按题意输出答案
输入样例 如case1.in内容如下 I am a student. My school is SCAU. It is a beau- tiful university. I like it.
输出样例 a 2 i 2 is 2 it 2 am 1
代码如下
#include stdio.h
#include string.h
#include stdlib.h#define MAX_WORDS 10005
#define MAX_WORD_LEN 25char words[MAX_WORDS][MAX_WORD_LEN]; // 存放各个单词
int count[MAX_WORDS]; // 记录每个单词出现的次数
int wordCount 0; // 不同单词的个数// 查找单词在数组中的位置找不到则插入
void searchAndInsert(char word[])
{for (int i 0; i wordCount; i){if (strcmp(word, words[i]) 0){count[i]; // 单词已存在增加计数return;}}// 单词不存在插入数组strcpy(words[wordCount], word);count[wordCount];wordCount;
}// 初始化函数读取文件内容并统计单词
void initialize()
{FILE *file;char ch;char word[MAX_WORD_LEN];int pos 0;int flag 0; // 标记是否遇到字母int flag1 0; // 标记是否遇到连接符号if ((file fopen(case1.in, r)) NULL){perror(文件打开失败);exit(EXIT_FAILURE);}while ((ch fgetc(file)) ! EOF){if (flag1 ch ! \n flag) // 遇到连接符号且当前字符不是回车同时已经遇到字母{word[pos] \0; // 将当前字符串插入数组searchAndInsert(word);flag 0;pos 0;flag1 0;}if (A ch ch Z){ch ch 32; // 转换为小写word[pos] ch;flag 1;flag1 0;}else if (ch a ch z){word[pos] ch;flag 1;flag1 0;}else if (ch -){if (flag)flag1 1;continue;}else if ((flag !flag1)){word[pos] \0;searchAndInsert(word);flag 0;pos 0;}if (ch \n flag1){flag1 0;}}fclose(file);
}int main()
{memset(count, 0, sizeof(count));memset(words, 0, sizeof(words));initialize();int n 5;while (n-- n wordCount) // 只取前五个或全部单词{int maxIndex 0;for (int i 1; i wordCount; i){if (count[i] count[maxIndex] || (count[i] count[maxIndex] strcmp(words[i], words[maxIndex]) 0)){maxIndex i;}}printf(%s %d\n, words[maxIndex], count[maxIndex]);count[maxIndex] 0; // 输出后将最大值清零找次大值}return 0;
}总结 完结撒花 ~~ 忘记这个题目是参考哪位大佬的去年写的太久了如果需要引用原文欢迎致信