首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

求教C,该怎么处理

2013-10-21 
求教C在文本文档中是一篇英文文章,要求计算其中的单词数,和单词重复出现的次数,并且排序输出[解决办法]#in

求教C
  在文本文档中是一篇英文文章,要求计算其中的单词数,和单词重复出现的次数,并且排序输出
[解决办法]
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#define NHASH  29989//比总数 大一些的 质数,这个例子单词的总数为 299131
#define MULT 31 //  单个单词可以选择的数目大一些的质数。 这个例子为英语字母26
typedef struct node *nodeptr;
typedef struct node{
    char *word;
    int count;
    nodeptr next;
}hashnode;
nodeptr bin[NHASH];
unsigned int hash(const char *p)
{
    unsigned int h=0;
    for(;*p;++p)
    {
        h=MULT*h+*p;
    }
    return h%NHASH;
}
void incword(const char * buf)
{
    unsigned int h=hash(buf);
    nodeptr p;
    for(p=bin[h];p!=NULL;p=p->next)
    {
        if(strcmp(buf,p->word)==0 )
        ++(p->count);
        return ;
    }
    p=(nodeptr)malloc(sizeof(hashnode));
    p->word=(char *)malloc(strlen(buf)+1);
    p->count=1;
    strcpy(p->word,buf);
    p->next=bin[h];
    bin[h]=p;
}
int main(void)
{
    int i=0,sum=0;
    char buf[128];
    nodeptr p;
    freopen("deep_cpp.txt","r",stdin);
    for(i=0;i<NHASH;++i)
    {
        bin[i]=NULL;

    }

    while(scanf("%s",buf)!=EOF)
    {
        incword(buf);
        ++sum;
    }
    for(i=0;i<NHASH;++i)
    {
        for(p=bin[i];p!=NULL;p=p->next)
        {
            printf("%s\t%d\n",p->word,p->count);
        }
    }
    printf("total %d words\n",sum);
    return 0;
}

热点排行