C語言沒有內置的字典數據結構,但可以使用其他數據結構來實現字典,比如數組、鏈表或哈希表。以下是使用哈希表實現字典的一種常見方式:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_SIZE 100
typedef struct {
char key[50];
char value[50];
} KeyValuePair;
typedef struct {
KeyValuePair data[MAX_SIZE];
int count;
} Dictionary;
void initialize(Dictionary* dictionary) {
dictionary->count = 0;
}
void insert(Dictionary* dictionary, const char* key, const char* value) {
if (dictionary->count >= MAX_SIZE) {
printf("Dictionary is full.\n");
return;
}
strcpy(dictionary->data[dictionary->count].key, key);
strcpy(dictionary->data[dictionary->count].value, value);
dictionary->count++;
}
const char* find(Dictionary* dictionary, const char* key) {
for (int i = 0; i < dictionary->count; i++) {
if (strcmp(dictionary->data[i].key, key) == 0) {
return dictionary->data[i].value;
}
}
return NULL;
}
int main() {
Dictionary dictionary;
initialize(&dictionary);
insert(&dictionary, "apple", "果實");
insert(&dictionary, "banana", "香蕉");
insert(&dictionary, "cherry", "櫻桃");
const char* value = find(&dictionary, "banana");
if (value) {
printf("The Chinese meaning of 'banana' is '%s'\n", value);
} else {
printf("Cannot find the word 'banana'\n");
}
return 0;
}
該示例演示了使用哈希表實現的簡單字典數據結構。Dictionary 結構包含一個 KeyValuePair 數組,用于存儲鍵值對。通過 insert 函數可以向字典中插入新的鍵值對,通過 find 函數可以查找指定鍵的值。