C++经典题目二:统计一篇英文文章中的单词个数
2011-09-30 20:30
471 查看
要求:统计处一篇英文文章中的不同的单词,并得到单词个数。
用一个单向链表保存所出现的单词,注意几点:1)文件输入输出;2)字符串处理;3)链表数据结构
再看代码——算法实现如下:
用一个单向链表保存所出现的单词,注意几点:1)文件输入输出;2)字符串处理;3)链表数据结构
再看代码——算法实现如下:
//================================================================ // 读入一篇英文文章,统计其中的单词,并得到每个单词出现的次数 // 链表的应用 //================================================================ #include "stdafx.h" #include "string.h" #include <malloc.h> typedef struct _link // 定义该链表是为了存储不重复出现的单词 { char* ch; int num; _link* next; }link; int _tmain(int argc, _TCHAR* argv[]) { // 读入一个txt.文件操作 FILE *fp; fp = fopen("test1.txt","r"); char word[1025]; int pos = 0; // 亦可用 size_t类型 char c; link *head, *pnow, *ptmp; head = pnow = ptmp = NULL; while (!feof(fp)) { c = fgetc(fp); //逐个获取的字符 if ((c>='a'&&c<='z')||(c>='A'&&c<='Z')||(c=='\'')) word[pos++]=c; else if (pos>0) { word[pos] = '\0'; // 链表遍历,比较链表中的节点值与当前单词 ptmp = head; while (ptmp) { if (strcmp(word, ptmp->ch)==0) { ptmp->num++; break; } ptmp = ptmp->next; } // 如果链表中没有当前单词,在链表末尾插入节点 if (ptmp == NULL) { ptmp = (link*)malloc(sizeof(link)); //注意一下两行的用法 ptmp->ch = (char*)malloc(pos); strcpy(ptmp->ch, word); ptmp->num=1; ptmp->next = NULL; if (pnow) // 插入当前节点为末节点 { pnow->next = ptmp; pnow = ptmp; } else // 此处为第一次出现单词的时候 head = pnow = ptmp; } pos=0; } } fclose(fp); // 对文件进行操作,关闭文件 // 读取链表,输出单词及其出现的个数 ptmp = head; FILE *fp1 = fopen("result.txt","w"); while (ptmp) { fprintf(fp1,"%d\t%s\n", ptmp->num, ptmp->ch); ptmp = ptmp->next; } fclose(fp1); return 0; }
相关文章推荐
- 统计一篇英文文章内每个单词出现频率,并返回出现频率最高的前10个单词及其出现次数
- 统计一篇英文文章中单词出现的频数
- 统计一篇英文文章中所有的单词以及出现的次数
- java实现读取一篇英文文章,统计其中每个单词出现的次数并排序输出
- 统计一篇文章中长度大于6个的英文单词个数【重复的单词只算一次】。
- 统计一篇英文文章中的单词数
- C++语言,统计一篇英文文章中的单词数(用正则表达式实现)
- 统计一篇英文文章中出现次数最多的前五个单词
- Java统计一篇文章中出现次数最多的汉字或英文单词 又出现次数的统计
- 给定一篇英文文章,找出其中使用频率最高的英语单词。
- C++英文单词统计小程序
- 如何统计在一篇文章中某个单词出现了几次,以及第一次出现的位置
- N个任务掌握java系列之统计一篇文章中单词出现的次数
- 一篇经典的TCP/IP基础知识英文文章
- 7.10 有一篇文章,共有3行文字,每行有80个字符。要求分别统计出其中英文大写字母、小写字母、数字、空格以及其他字符的个数。
- 统计一篇文章中单词出现的频率
- 统计英文文章中单词出现次数
- 统计一篇英文中每个单词出现的次数
- Java统计一篇英文单词出现次数
- F# 统计一段英文文章中不同单词出现的次数