版权声明:本文为小斑马伟原创文章,转载请注明出处!
主要步骤:
- 创建结构体存储单词和翻译
- 读取单词 格式化存储对应的堆空间中
- 单词查找
- 销毁堆空间
头部文件
//单词和翻译的结构体
#pragma once
#include<stdlib.h>
//单词和翻译的结构体
typedef struct DICT
{
char* word;
char* trans;
}dict;
//索引的结构体
typedef struct POSTION
{
int start;
int end;
}pos;
dict* list = NULL;
pos* index = NULL;
//函数声明
//获取单词库中的单词和翻译
int GetWord();
//查找单词
int SearchWord(char* word,char* trans,int idx);
//销毁数据
void DestorySpace();
二、核心代码
int GetWord() {
FILE* fp = fopen("D:/d.txt", "r");
if (!fp) {
printf("加载单词库失败\n");
return -1;
}
list = (dict*)malloc(sizeof(dict)* SIZE);
index = (pos*)malloc(sizeof(pos)* 27);
char flag = 'a'; //记录当前索引标志位
index[0].start = 0; //记录a的索引
index[0].end = 0;
int idx = 0; //字母对应的索引
int i = 0; //数组小标
char* temp = (char*)malloc(sizeof(char)* 1024);
while (!feof(fp)) {
memset(temp, 0, 1024);
fgets(temp, 1024, fp);
//开辟单词的堆空间 #a\n
//去掉\n
temp[strlen(temp) - 1] = 0;
list[i].word = (char*)malloc(sizeof(char)*strlen(temp));
//将单词放在指定堆空间中
strcpy(list[i].word, &temp[1]);
//创建索引
//0-25 index[0].start index[0].end b
if (idx != 26) {
if (list[i].word[0] == flag) { //首字母是否为a
index[idx].end++;
}
else {
idx++;
index[idx].start = index[idx - 1].end;
index[idx].end = index[idx - 1].end + 1;
flag++;
}
}
memset(temp, 0, 1024);
fgets(temp, 1024, fp); //Trans:srt - :字母A\n
//去掉\n
temp[strlen(temp) - 1] = 0;
list[i].trans = (char*)malloc(sizeof(char)*strlen(temp) -5);
strcpy(list[i].trans, &temp[6]);
i++;
}
//释放和关闭文件
free(temp);
fclose(fp);
//记录中文的索引
index[26].start = index[26].end;
index[26].end = SIZE;
for (int i = 0; i < 27; i++) {
printf("%c的起始位置: %d\n", 'a' + i, index[i].start);
printf("%c的结束位置: %d\n", 'a' + i, index[i].end);
}
for (int i = 0; i < SIZE; i++) {
printf("%s\n", list[i].word);
printf("%s\n", list[i].trans);
}
return i;
}
三、单词查找
int SearchWord(char* word, char * trans,int idx) {
if (!word || !trans) {
printf("输出发生异常\n"); //exit(-1)
return -1;
}
for (int i = index[idx].start; i < index[idx].end; i++) {
//如果用户输入的单词和词库中相同返回单词对应的翻译
if (!strcmp(word, list[i].word)) {
strcpy(trans, list[i].trans);
return 0;
}
}
return 1;
}
四、释放内存
void DestorySpace()
{
if (list == NULL)
return;
if (!index)
{
free(index);
index = NULL;
}
for (int i = 0; i < SIZE; i++) {
free(list[i].word);
free(list[i].trans);
}
free(list);
list = NULL;
}
网友评论