输入: hello 输出: helohtml
第一种实现: 不新开数组, 也就是原地去重.数组
#include <stdio.h> #include <string.h> void removeDuplicate(char str[]); int main (void) { char name[] = "hello"; removeDuplicate(name); printf("%s\n", name); return 0; } void removeDuplicate(char str[]) { int len = strlen(str); int p = 0; int i; int j; for (i=0; i<len; i++) { if (str[i] != '\0') { str[p++] = str[i]; for (j=i+1; j<len; j++) { if (str[i] == str[j]) { str[j] = '\0'; } } } } str[p] = '\0'; }
上面的代码一共出现了3次'\0', 前2次的'\0'没有什么特殊含义, 能够替换成任何在所给字符串中
不会出现的字符. 最后一个'\0'则是C语言中特有的, 是字符串结束标志.
就是把全部重复的元素标记成'\0', 那么剩下的元素则是不重复的元素, 经过变量p, 把这些元素从新
添加到结果字符串中便可.post
第二种实现: 新开数组实现.code
#include <stdio.h> #include <string.h> void removeDuplicate(char str[], char res[]); int main (void) { char name[20] = "sdfsssww"; char res[20]; removeDuplicate(name, res); printf("%s\n", res); return 0; } void removeDuplicate(char str[], char res[]) { int slen = strlen(str); int rlen = 0; int flag; // 元素重复标志 int i; int j; for (i=0; i<slen; i++) { flag = 0; for (j=0; j<rlen; j++) { // 每次都把结果数组遍历一遍, 与当前字符比较, 有重复 // 就标记为 1 if (res[j] == str[i]) flag = 1; } if (flag == 0) { res[rlen++] = str[i]; } } res[rlen] = '\0'; }
第三种, 一层循环, 开个ASCII数组进行标记htm
#include <stdio.h> #include <string.h> void removeDuplicate(char str[]); int main (void) { char name[] = "wwwwsssspp"; removeDuplicate(name); printf("%s\n", name); return 0; } void removeDuplicate(char str[]) { int len = strlen(str); int ascii[128] = {0}; int p = 0; int i; for (i=0; i<len; i++) { if (ascii[str[i]] == 0) { ascii[str[i]] = 1; str[p++] = str[i]; } } str[p] = '\0'; }
第四种, 也是新开ASCII数组进行标记, 实现去2重, 好比输入: sswqswww, 输出: sswqswci
#include <stdio.h> #include <string.h> void removeDuplicate(char str[]); int main (void) { char name[] = "sswqswww"; removeDuplicate(name); printf("%s\n", name); return 0; } void removeDuplicate(char str[]) { int len = strlen(str); int ascii[128] = {0}; int p = 0; int i; for (i=0; i<len; i++) { if (ascii[str[i]] != 2) { ascii[str[i]]++; str[p++] = str[i]; } } str[p] = '\0'; }
第五种, 上面的代码简单改下, 既能够实现去n重rem
#include <stdio.h> #include <string.h> void removeDuplicate(char str[], int n) int main (void) { char name[] = "sswqswww"; removeDuplicate(name, 2); printf("%s\n", name); return 0; } void removeDuplicate(char str[], int n) { int len = strlen(str); int ascii[128] = {0}; int p = 0; int i; for (i=0; i<len; i++) { if (ascii[str[i]] != n) { ascii[str[i]]++; str[p++] = str[i]; } } str[p] = '\0'; }