可以使用一个哈希表来存储字符串中出现的字符,并遍历字符串删除重复字符。具体步骤如下:
声明一个哈希表,用于存储字符串中出现的字符。遍历字符串,对于每个字符:如果当前字符在哈希表中已经存在,则删除当前字符。否则,将当前字符加入哈希表中。最后,将处理后的字符串输出即可。下面是一个示例代码:
#include <stdio.h>#include <string.h>void removeDuplicates(char* str) { int hash[256] = {0}; // 哈希表,用于存储字符出现的次数 int j = 0; // 用于记录处理后的字符串下标 for (int i = 0; i < strlen(str); i++) { if (hash[(int)str[i]] == 0) { str[j] = str[i]; hash[(int)str[i]] = 1; j++; } } str[j] = '\0'; // 结尾添加字符串结束符}int main() { char str[] = "hello world"; printf("原始字符串:%s\n", str); removeDuplicates(str); printf("删除重复字符后的字符串:%s\n", str); return 0;}运行上面的代码,可以看到输出结果为:
原始字符串:hello world删除重复字符后的字符串:helo wrd这样就实现了删除字符串中的重复字符的功能。


