C语言实现字典功能实例
时间: 2023-09-02 12:07:44 浏览: 280
C语言字典树创建和搜索示例
好的,下面是一个简单的 C 语言字典功能的实现示例:
```c
#include <stdio.h>
#include <string.h>
// 定义一个结构体,表示字典中的一个词条
struct Entry {
char word[20];
char definition[100];
};
// 定义一个函数,用于在字典中查找给定的单词
void lookup(struct Entry dictionary[], char searchWord[]) {
int i;
for (i = 0; i < 10; i++) {
if (strcmp(searchWord, dictionary[i].word) == 0) {
printf("%s\n", dictionary[i].definition);
return;
}
}
printf("Sorry, the word is not in the dictionary.\n");
}
int main() {
// 定义一个字典,包含 10 个词条
struct Entry dictionary[10] = {
{"apple", "a round fruit with red, yellow, or green skin and firm white flesh"},
{"banana", "a long curved fruit which grows in clusters and has soft pulpy flesh and yellow skin when ripe"},
{"cat", "a small domesticated carnivorous mammal with soft fur, a short snout, and retractable claws"},
{"dog", "a domesticated carnivorous mammal with a barking voice and a short coat"},
{"elephant", "a very large animal with a long nose called a trunk, used for grasping objects, and two long curved ivory tusks"},
{"fish", "a cold-blooded aquatic vertebrate with scales and gills"},
{"grape", "a small sweet or sour fruit with a thin skin and small seeds"},
{"horse", "a large four-legged animal with a mane and tail"},
{"ice cream", "a cold sweet food made from frozen milk or cream"},
{"jacket", "an outer garment worn by both men and women, typically having sleeves and a fastening down the front"}
};
// 从用户输入中读取要查找的单词,然后在字典中查找
char searchWord[20];
printf("Please enter a word to look up: ");
scanf("%s", searchWord);
lookup(dictionary, searchWord);
return 0;
}
```
在这个例子中,我们定义了一个结构体 `Entry`,表示字典中的一个词条,包含一个单词和一个定义。然后我们定义了一个函数 `lookup`,接受一个字典数组和一个要查找的单词,用于在字典中查找给定的单词。在 `lookup` 函数中,我们使用了 `strcmp` 函数来比较两个字符串是否相等。最后,在 `main` 函数中,我们定义了一个包含 10 个词条的字典数组 `dictionary`,并从用户输入中读取要查找的单词,然后调用 `lookup` 函数在字典中查找。
阅读全文