您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
在C语言中,字符串的哈希计算是将一个字符串映射到一个整数值,通常用于在数据结构(如哈希表)中快速查找和存储
unsigned int simple_hash(const char *str) {
unsigned int hash = 0;
for (int i = 0; str[i] != '\0'; i++) {
hash += str[i];
}
return hash;
}
unsigned int djb2_hash(const char *str) {
unsigned int hash = 5381;
int c;
while ((c = *str++)) {
hash = ((hash << 5) + hash) + c; // hash * 33 + c
}
return hash;
}
unsigned int sdbm_hash(const char *str) {
unsigned int hash = 0;
int c;
while ((c = *str++)) {
hash = c + (hash << 6) + (hash << 16) - hash;
}
return hash;
}
#include<stdio.h>
#include <stdlib.h>
#include<string.h>
typedef struct HashNode {
char *key;
char *value;
struct HashNode *next;
} HashNode;
HashNode *create_node(const char *key, const char *value) {
HashNode *node = (HashNode *)malloc(sizeof(HashNode));
node->key = strdup(key);
node->value = strdup(value);
node->next = NULL;
return node;
}
void insert(HashNode **table, const char *key, const char *value, unsigned int (*hash_func)(const char *)) {
unsigned int index = hash_func(key) % 100;
HashNode *node = table[index];
if (!node) {
table[index] = create_node(key, value);
} else {
while (node->next) {
if (strcmp(node->key, key) == 0) {
free(node->value);
node->value = strdup(value);
return;
}
node = node->next;
}
node->next = create_node(key, value);
}
}
char *get(HashNode **table, const char *key, unsigned int (*hash_func)(const char *)) {
unsigned int index = hash_func(key) % 100;
HashNode *node = table[index];
while (node) {
if (strcmp(node->key, key) == 0) {
return node->value;
}
node = node->next;
}
return NULL;
}
int main() {
HashNode *table[100] = {NULL};
insert(table, "hello", "world", djb2_hash);
printf("Value of 'hello': %s\n", get(table, "hello", djb2_hash));
return 0;
}
这个示例中,我们创建了一个简单的哈希表,并使用DJB2哈希函数将字符串存储在哈希表中。然后,我们使用相同的哈希函数从哈希表中获取字符串。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。