计算一行字符中单词的词频
其中计算词频用二叉树计算
2008年最后一题(有几个注意点)
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct BTnode
{
//char *ch;
char ch[20];
int count;
struct BTnode *lchild,*rchild;
}BTnode;
void insert(BTnode **p,char *s)
{
if((*p)==NULL)
{
(*p)=(BTnode*)malloc(sizeof(BTnode));
(*p)->lchild=(*p)->rchild=NULL;
strcpy((*p)->ch,s);
(*p)->count=1;
}
else
{
if(strcmp(s,(*p)->ch)==0)
(*p)->count++;
else if(strcmp(s,(*p)->ch)>0)
insert(&((*p)->rchild),s);
else
insert(&((*p)->lchild),s);
}
}
void getresult(BTnode *p,int word)
{
if(p!=NULL)
{
printf("%s的频度为%f\n",p->ch,(1.0)*p->count/word);
getresult(p->lchild,word);
getresult(p->rchild,word);
}
}
int main()
{
int i=0,j=0,word=0;
char s[200],temp[10];
BTnode *p=NULL;
gets(s);
while(s[i-1]!='\0')
{
if((s[i]>='a'&&s[i]<='z')||(s[i]>='A'&&s[i]<='Z'))
temp[j++]=s[i++];
else
{
temp[j]='\0'; //修改
insert(&p,temp);
j=0;
temp[j]='\0'; //修改
i++; //修改
word++;
}
}
getresult(p,word);
system("pause");
return 0;
}
//l am li lei and l come from china still lei and from gg and 输入
注意注意注意!!!
本题有个大坑:
通过指针调用字符串的时候不能使用strcpy复制,必须用字符数组(主程序中结构体注释掉了),因为strcpy的原来类型中有个const。比如下面的程序,换程注释的就不行执行
#include<stdio.h>
#include<string.h>
int main()
{
//char *s=NULL;
char s[200];
char *a="abc";
strcpy(s,a);
puts(s);
return 0;
}