SCAUoj综合性实验
Last One !
文章目录
- 1109 综合实验:文件操作与字符处理
- 总结
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 25
char 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;
}
总结
完结撒花 ~~ 忘记这个题目是参考哪位大佬的(去年写的太久了),如果需要引用原文欢迎致信