您的位置:首页 > 编程语言 > C语言/C++

C++经典题目二:统计一篇英文文章中的单词个数

2011-09-30 20:30 471 查看
要求:统计处一篇英文文章中的不同的单词,并得到单词个数。

用一个单向链表保存所出现的单词,注意几点: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;
}








                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: