在C语言中,删除字符串中的重复字符可以通过多种方法实现。以下是一个使用哈希表(散列表)来记录已经遇到的字符,并构建一个新的不包含重复字符的字符串的方法。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 函数声明
char* removeDuplicates(const char* str);
int main() {
const char* input = "hello world";
char* result = removeDuplicates(input);
printf("Original: %s\n", input);
printf("Without duplicates: %s\n", result);
free(result); // 释放动态分配的内存
return 0;
}
char* removeDuplicates(const char* str) {
int length = strlen(str);
char* result = (char*)malloc(length + 1); // 分配足够的空间
if (!result) return NULL; // 内存分配失败处理
int index = 0;
int seen[256] = {0}; // 假设字符是ASCII
for (int i = 0; i < length; ++i) {
if (!seen[(unsigned char)str[i]]) { // 检查字符是否已见过
result[index++] = str[i];
seen[(unsigned char)str[i]] = 1; // 标记为已见
}
}
result[index] = '\0'; // 添加字符串结束符
return result;
}
malloc
为结果字符串分配内存。seen
来记录哪些字符已经出现过,因为ASCII字符集共有256个字符。seen
数组中标记过。如果没有,则将其添加到结果字符串中,并在seen
中标记该字符。通过这种方法,可以有效地从C语言中的字符串删除重复字符。
领取专属 10元无门槛券
手把手带您无忧上云