可以通过遍历字符串来删除重复字符,具体步骤如下:
下面是一个示例代码:
#include <stdio.h> #include <string.h> void removeDuplicates(char *str) { int len = strlen(str); char result[len]; int index = 0; for (int i = 0; i < len; i++) { int j; for (j = 0; j < index; j++) { if (str[i] == result[j]) { break; } } if (j == index) { result[index++] = str[i]; } } result[index] = '\0'; strcpy(str, result); } int main() { char str[] = "hello world"; printf("Original string: %s\n", str); removeDuplicates(str); printf("String after removing duplicates: %s\n", str); return 0; }
运行以上代码,输入为 “hello world”,输出为 “helo wrd”。