单词检索c语言注释,文本文件单词的检索与计数解决办法

C/C++ code// 统计一篇文章中每个单词出现的次数

#include

#include

#include

#include

struct node{

char *s;

int num;

node *next;

};

node * insert(node *&head,node *p) //构建链表

{

node *q,*q1;

if(!head) //建头

{

head=p;

p->next=0;

p->num=1;

return head;

}

q1=q=head;

while(q) //对比单词

{

if(strcmp(q->s,p->s))

{

q1=q;q=q->next;

}

else

{

q->num+=1;

return head;

}

}

if(!q)q1->next=p; //插入尾部

return head;

}

node *readfile() //读文件

{

char *p=NULL,*q=p,*q1,e;

node *head=0,*head1=0,*word;

FILE *fp;

fp = fopen("word.txt","r");

if(fp == NULL)

{

printf("file open error");

exit(0);

}

while(fgets(p,100,fp)!=NULL)

{

while(!isalpha(*p))++p; //指向单词开始处

q1=p;

while(isalpha(*q1)&&*q1)++q1; //指向单词尾处

e=*q1; //留COPY

*q1='{post.content}'; //置结尾符

word=new node;

word->s=new char[strlen(p)+1];

strcpy(word->s,p); //放入单词

word->num=1;

word->next=0;

head=insert(head,word); //插入链表

word=0;p=q1; *p=e;

} //完成循环后所有单词被无序插入head中.

node *hh=head;

while(hh)

{

word=new node;

word->s=new char[strlen(hh->s)+1];

strcpy(word->s,hh->s);

word->num=hh->num;

word->next=0;

hh=hh->next;

}

while(head) //回收空间

{

hh=head;

head=hh->next;

delete hh->s;

delete hh;

}

return head1;

}

int main()

{

node *result = readfile(); //读文件

node *p=result;

while(p)

{

printf("单词:[%s]出现次数:[%d]", p->s, p->num);

p=p->next;

}

return 0;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值