统计文件中每个单词的个数--C语言实现
来源:互联网 发布:windows phone 百度云 编辑:程序博客网 时间:2024/05/22 05:07
#include <stdio.h>#include <stdlib.h>#include <string.h>//这个程序是再Linux环境下写的,用到了命令行参数 struct Word //声明一个结构体,分别存储单词和对应单词的个数 {size_t time;char word[20];};void Copy(struct Word *array, FILE *read, const int length);void Count_for_word(struct Word *array, const int length);int main(int argc, char *argv[]){char word[20];int length = 0, ch;FILE *read;struct Word *array;if (argc < 2 || argc > 2){printf("usage: %s filename\n", argv[0]);exit(EXIT_FAILURE);}if ((read = fopen(argv[1], "r")) == NULL){printf("open file failure\n");exit(EXIT_FAILURE);}while (fscanf(read, "%s", &word) != EOF) //测试是否读到文件末尾 ++length; //统计文本中单词的个数 rewind(read); //把文件指针置为文本开始的位置,并清除错位信息 array = malloc(sizeof(struct Word) * length);Copy(array, read, length);return 0;}void Copy(struct Word *array, FILE *read, const int length) //该函数的作用是把文本中的单词复制到数组中 {char ch, word[20];int i = 0, j;while (fscanf(read, "%s", &word) != EOF) {strcpy(array[i].word, word);++i; //移动数组的下标 }fclose(read);Count_for_word(array, length);}void Count_for_word(struct Word *array, const int length) //统计单词的个数 {int i, j;for (i = 0; i < length; i++){array[i].time = 1;for (j = i+1; j < length; j++){if (strcmp(array[i].word, array[j].word) == 0){++array[i].time; //如果遇到相同的单词,就把相应的结构体部分增加 1 strcpy(array[j].word, " "); //并把该单词置为空,应为已经读取到数组中了,所以这里改变的是数组的数据,不影响文本数据 }}}printf("the file have %d word\n\n", length);for (i = 0; i < length; i++)if (strcmp(array[i].word, " ") != 0)printf("%-5s occurrs %-3d %s\n", array[i].word, array[i].time, ((array[i].time > 1) ? "times" : "time"));}
阅读全文
0 0
- 统计文件中每个单词的个数--C语言实现
- 统计文本中每个单词的个数
- C/C++语言统计文件中单词出现个数
- 【C语言助教】统计文本中单词的个数!
- C语言统计一个字符串中单词的个数
- C语言-统计一行句子中单词的个数
- C语言算法--统计字符串中单词的个数
- 统计一个字符串中单词的个数(C语言)
- C语言统计输入的单词个数
- 统计文件中单词个数--c++实现
- Java测验 统计字符串中每个“单词”的个数
- C语言 统计单词个数
- C语言统计单词个数
- 统计文件中每个字母的个数
- C语言K&R习题系列——统计文档中每个单词所包含的字母个数,以直方图形式输出
- C语言实现文件单词统计
- C语言用二叉树统计一个源文件中每个单词的次数
- 用c语言统计文件中某个汉字的个数
- java基础知识整合
- 获取运行当前进程的用户名
- php curl post raw json参数
- 旅游项目(二)初涉Bootstrap
- Python3 基本数据类型
- 统计文件中每个单词的个数--C语言实现
- jvm
- spring 使用c3po连接池
- 总结
- [BZOJ]3192: [JLOI2013]删除物品 树状数组
- WebView
- 快速编译出WebRTC for Android 的一次记录
- 2017.9.17 胡策题 【题解 + 总结】【NOIP模拟】
- sql面试题