我们先从最简单的开始,即只有两个单词的词典。
1 原始版本
新建一个translation.c的文件,内容如下:
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
typedef struct _dict { //一个单词对应一个结构
char english[256];
char chinese[256];
} Dict;
Dict* dict_init() {
//hello 你好
//world 世界
Dict* dict = (Dict*)malloc(sizeof(Dict) * 2);
strcpy(dict[0].english, "hello"); //字符串复制
strcpy(dict[0].chinese, "你好");
strcpy(dict[1].english, "world");
strcpy(dict[1].chinese, "世界");
return dict;
}
void search(Dict* dict, char* english, int n)
{
for (int i = 0; i < n; i++)
{
if (strcmp(dict[i].english, english) == 0)
{
printf("OK!The Chinese word is:%s", dict[i].chinese);
printf("\n");
return ;
}
}
printf("There is no %s\n", english);
}
void translate() {
Dict* dict = dict_init();
int ret = 0;
char english[256];
while (1)
{
printf("Please Enter the world you want to search:");
fgets(english, sizeof(english), stdin);
english[strlen(english) - 1] = 0;
printf("%s\n", english);
search(dict, english, 2);
}
free(dict);
}
新建一个main.c的文件,内容如下:
int main()
{
translate();
return 0;
}
main函数没啥好讲的,主要就是translation.c,它先定义了一个结构体类型,包含了中英文数组,接下来就是字典初始化函数dict_init
、查找函数search
、翻译函数translation
2 内存优化版
上面的代码有比较严重的资源浪费,因为每个单词都给分配256个字节,假如字典里有两万个单词,则会占用巨大的内存空间,这里对这个问题进行优化,代码如下:
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
typedef struct _dict {
char * english;
char * chinese;
} Dict;
Dict* dict_init() {
//hello 你好
//world 世界
Dict* dict = (Dict *)malloc(sizeof(Dict) * 2);
char* p[] = { "hello" , "你好" , "world" , "世界" };
int len = 0;
for (int i = 0; i < 2; i++)
{
len = strlen(p[i]);
dict[i].english = (char*)malloc(len + 1);
strcpy(dict[0].english, p[i]);
len = strlen(p[i+1]);
dict[i].chinese = (char*)malloc(len + 1);
strcpy(dict[0].chinese, p[i+1]);
}
return dict;
}
void search(Dict* dict, char* english, int n)
{
for (int i = 0; i < n; i++)
{
if (strcmp(dict[i].english, english) == 0)
{
printf("OK!The Chinese word is:%s", dict[i].chinese);
printf("\n");
return;
}
}
printf("There is no %s\n", english);
}
void translate() {
Dict* dict = dict_init();
int ret = 0;
char english[256];
while (1)
{
printf("Please Enter the world you want to search:");
fgets(english, sizeof(english), stdin);
english[strlen(english) - 1] = 0;
printf("%s\n", english);
search(dict, english, 2);
}
for (int i = 0; i < 2; i++)
{
free(dict[i].chinese);
free(dict[i].english);
}
free(dict);
}
这里结构体里面只定义字符指针,遇到单词,根据单词的长度分配内存。
这里要注意,最后释放内存的时候,不能单单释放dict,需要由内到外的顺序,否则会内存泄漏。
我们目前做的词典还比较原始,下一个练习将会制作一个包含十几万个单词的词典。