索引查找之英语词典(C语言实现)
/** 题目:英语词典。所有的单词存放在dictionary.txt中。输入一个英文单词,在词典中查找这个单词,
* 若找到显示这个单词的中文意思,显示此单词不存在。
* 思路:以字母顺序建立索引表。
*
*/
http://dl.iteye.com/upload/attachment/498467/46ab102a-3556-3dfc-adb1-8f429a0d3c0a.jpg
/* * 题目:英语词典。所有的单词存放在dictionary.txt中。输入一个英文单词,在词典中查找这个单词, * 若找到显示这个单词的中文意思,显示此单词不存在。 * 思路:以字母顺序建立索引表。 * */#include<stdio.h>#include<stdlib.h>#include<string.h>#define MAX_LENGTH 26 //索引表最大长度#define WORD_LENGTH 20 //单词最大长度//单词typedef struct Word{char English;char Chinese;struct Word *next;}Word,*PWordList;//索引项typedef struct {char ch; //索引值PWordList pWord;//指向单词链表}Index;Index indexTable;//索引表int length; //索引表长度//二分查找法查找索引表,若找到返回下标,查找失败,返回要插入的位置int binarySearch(char ch,int low,int high){int mid=(low+high)/2;if(low>high)return low; if(indexTable.ch==ch)return mid;else if(indexTable.ch>ch)binarySearch(ch,low,mid-1);else binarySearch(ch,mid+1,high);}//从文件中读入单词,建立字典void createDictionary(){FILE *fp;char str;PWordList Pword=0;int i,j,m=0,index;if((fp=fopen("document/dictionary.txt","r"))==NULL){printf("can not open file!\n");exit(0);}while(!feof(fp)){ Pword=(PWordList)malloc(sizeof(Word)); i=j=m=0; fgets(str,WORD_LENGTH*3,fp); while(str!='\n'){ if(m==0){ if(str==' '){ m=1; Pword->English='\0'; j=0;}else{if(str>='A'&&str<='Z')str+=32; Pword->English=str;}} if(m==1){ if(str!=' ') Pword->Chinese=str;} i++;}Pword->Chinese='\0';//取单词的首字母,查找索引表,若存在,把这个单词插入这个索引指向的分组中,不存在,则插入索引和单词 index=binarySearch(Pword->English,0,length-1); if(indexTable.ch==Pword->English){//查到该索引 Pword->next=indexTable.pWord; indexTable.pWord=Pword;}else{//查找失败 for(i=length;i>=index;i--) indexTable=indexTable; length++; indexTable.ch=Pword->English; Pword->next=NULL; indexTable.pWord=Pword;} //printf("%-10s%-10s\n",word.English,word.Chinese);}if(fclose(fp)){printf("can not close file!\n");exit(0);}}//查找单词,不成功返回NULL,成功返回这个单词PWordList search(char *word){int i=0,index;PWordList p=0;PWordList pWord=NULL;while(word){if(word>='A'&&word<='Z')word+=32;i++;} index=binarySearch(word,0,length-1); if(indexTable.ch==word){//查到该索引p=indexTable.pWord; while(p){if(strcmp(p->English,word)==0){ pWord=(PWordList)malloc(sizeof(Word));strcpy(pWord->Chinese,p->Chinese);strcpy(pWord->English,p->English);pWord->next=NULL;break;}p=p->next;}}return pWord;}void main(){PWordList p=0;char word; createDictionary();printf("请输入要查找的单词:\n"); gets(word);p=search(word);if(p){printf("找到该单词:\n%-20s%-20s\n",p->English,p->Chinese);free(p);}elseprintf("你查找的单词不存在!\n");}
页:
[1]