#include "language_hashmap.h" #include "common.h" #include #include unsigned int _hash(HashTable *table,const char *key) { unsigned int hash = 0; while (*key) { hash = hash * 31 + *key++; } return hash % table->size; // 假设哈希表大小为101 } HashTable *create_hash_table(int size) { HashTable *table = (HashTable *)malloc(sizeof(HashTable)); table->size = size; table->ptable = (HashEntry **)malloc(size*sizeof(HashEntry *)); return table; } // 在哈希表中插入键值对 void insert_Newhash(HashTable *table, const char *key, char value[][32],int valuelens) { unsigned int index = _hash(table,key); HashEntry *entry = (HashEntry *)malloc(sizeof(HashEntry)); entry->key = strdup(key); entry->value=(char**)malloc(sizeof(char*)*valuelens); for (int i = 0; i < valuelens; i++) { entry->value[i] = strdup(value[i]); } entry->valueLength=valuelens; entry->next = table->ptable[index]; table->ptable[index] = entry; } // 在哈希表中查找键对应的值 const HashEntry*find_hash(HashTable *table, const char *key) { unsigned int index = _hash(table,key); HashEntry *entry = table->ptable[index]; while (entry) { if (strcmp(entry->key, key) == 0) { return entry; } entry = entry->next; } return 0; } // 释放哈希表占用的内存 void free_hash_table(HashTable *table) { for (int i = 0; i < table->size; i++) { HashEntry *entry = table->ptable[i]; while (entry) { HashEntry *temp = entry; entry = entry->next; free(temp->key); for (int i = 0; i < temp->valueLength; i++) { free(temp->value[i]); } free(temp->value); free(temp); } } free(table->ptable); free(table); } void replace_sequences(char *str, HashTable *table) { char *token = strtok(str, DELIMITER); char output[MAX_LEN] = ""; int output_len = 0; int token_len; while (token != 0) { if (token[0] == '$' && token[1] != '\0' && token[strlen(token) - 1] == '$') { // 去除包裹的`$`符号,并查找替换值 char *key = strdup(token + 1); // 跳过开头的`$` key[strlen(key) - 1] = '\0'; // 去除结尾的`$` const char *replacement; HashEntry* pEnty= find_hash(table, key); if (pEnty) { replacement=pEnty->value[__globalDeviceManage._global_device_info->product_language]; } free(key); // 释放key占用的内存 if (replacement) { // 将替换值追加到输出字符串中 strncat(output, replacement, MAX_LEN - output_len - 1); output_len += strlen(replacement); } else { // 如果没有找到替换值,可以选择保留原序列或抛出一个错误 // 这里选择保留原序列 strncat(output, DELIMITER, MAX_LEN - output_len - 1); strncat(output, token, MAX_LEN - output_len - 1); strncat(output, DELIMITER, MAX_LEN - output_len - 1); output_len += strlen(token) + 2 * strlen(DELIMITER); } } else { // 不是`$xxxx$`格式,直接追加到输出字符串中 strncat(output, token, MAX_LEN - output_len - 1); output_len += strlen(token); } token = strtok(0, DELIMITER); // 继续获取下一个token } // 将最终的输出字符串复制回原字符串 strncpy(str, output, output_len + 1); str[output_len] = '\0'; // 确保字符串以null结尾 }