自主实现一个词典

实现一个词典大致分为以下一个步骤:

(1)准备好一个文档,里面有对应的单词对照表(并且有序,因为要使用二分查找)。

(2)定义一条单词(英文,汉语,词性)的数据结构,在定义数据结构数组(因为有许多条单词)

(3)加载(即把文档里的每条单词,读取到定义好的数据结构数组中)

(4)查找,并且返回

代码如下:

  1  #include <stdio.h>
  2 #include <stdlib.h>
  3 #include <unistd.h>
  4 #include <string.h>
  5 #include <fcntl.h>

  7 //定义一个单词的结构体
  8 typedef struct dir
  9 {
 10     char english[30];
 11     char chinese[50];
 12     char cixing[6];
 13 }dict;
 14 
 15 //创建一个含有2个元素的结构体数组
 16 dict Words[8000];
 17 int count=0;

 19 //加载(即把文件里的单词数据,读到创建好的结构体数组中)
 20 void load()
 21 {
 22     FILE* fp=fopen("mydict.txt","r");
 23     if(fp==NULL)//打开文件失败
 24     {
 25         perror("fopen failure");
 26         exit(1);
 27     }
 28 
 29     //来到这,说明打开文件成功
 30     while(!feof(fp))//读取文件不结束
 31     {
 32         //从fp指向的文件中,以字符串、空格、字符串、空格、字符串方式读取内容,依次存在结构体对应的位置
 33         fscanf(fp,"%s\t%s\t%s",Words[count].english,Words[count].chinese,Words[count].cixing);
 34         count++;//记录当前读入的单词个数
 35     }
 36     fclose(fp);//用完关闭打开的文件
 37 }
 38 
 39 //查找
 40 int bin_research(char* buf)
 41 {
 42     int low=0;
 43     int hight=count;
 44     int mid=0;
 45 
 46     while(low<=hight)
 47     {
 48         int mid=low+((hight-low)>>1);
 49         if(strcmp(buf, Words[mid].english)<0)//说明buf中的单词比中间的小,则找前半部分
 50         {
 51             hight=mid-1;
 52         }
 53         else if(strcmp(buf,Words[mid].english)>0)//与上面是相反的
 54         {
 55             low=mid+1;
 56         }
 57         else//说明找到了
 58         {
 59             return mid;
 60         }
 61     }
 62     //来到这里,说明没找到
 63     return -1;
 64 }
 65 
 66 int main()
 67 {
 69     load();
 70 
 71     char buf[100];
 72     while(1)
 73     {
 74         printf("单词:");
 75         memset(buf,0x00,sizeof(buf));//清空缓存区
 76         scanf("%s",buf);//将输入的单词放入缓存区
 77 
 78         int ret=bin_research(buf);
 79         if(ret==-1)
 80         {
 81             printf("查无此单词\n");
 82         }
 83         else
 84         {
 85             printf("%s:\n",buf);
 86             printf("%s  ",Words[ret].chinese);
 87             printf("%s\n",Words[ret].cixing);
 88         }
 89     }
 90 
 91     return 0;
 92 }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值