怎样去掉字符串中的重复字符?
比如 S = "aaabbccca " 结果要得到 "abc " 怎么实现
[解决办法]
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int i, j;
char S[] = "aaabbccca ";
for (i=0; i <(int)strlen(S); i++)
{
for (j=i+1; j <(int)strlen(S); j++)
if (S[i] == S[j])
S[j] = ' ';
}
for (i=0; i <(int)strlen(S); i++)
if (S[i] != ' ')
printf( "%c ", S[i]);
return 0;
}
[解决办法]
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define n 20
int main()
{
int i, j,k=0;
char a[n]={0},b[n]={0};
printf( "please input the strings:\n ");
gets(a);
for (i=0; i <(int)strlen(a); i=j)
{
for (j=i+1; j <(int)strlen(a)&&a[i]==a[j]; j++);
b[k++]=a[i];
}
for (i=0; i <k; i++)
printf( "%c ", b[i]);
}
--------------------------
gcc下ok
空格也可以
[解决办法]
不开辟空间你复用那块内存就行了
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int isRepeat(char c, char* data, int len)
{
int i = 0;
for (; i < len; i++)
if (c == data[i])
return 1;
return 0;
}
int main()
{
// char data[sizeof(str)];
char str[] = "aaabbccca ";
int len = 0;
char* p = str;
while (*p)
{
if (!isRepeat(*p, str, len))
str[len++] = *p;
p++;
}
str[len] = '\0 ';
printf( "%s ", str);
return 0;
}