求C语言代码,删除字符串中重复字符

如输入"aabbcc",要求输出"abc"

第1个回答  2008-03-26
方法很多:
方法一
#include <stdio.h>;
#include <string.h>;
main()
{

char str[100],*p,*q,*r,c;
printf("请输入字符串:";
//gets(str);
scanf("%s",str);
for(p=str;*p;p++)
{
for(q=r=p;*q;q++)
if(*r>;*q)
r=q;
if(r!=q)
{
c=*r; *r=*p; *p=c;
}
} //冒泡排序的代码

printf("结果字符串为:%s\n",str);
for(p=str;*p;p++)
{
for(q=p+1;*p==*q;q++);
strcpy(p+1, q);
} //删除重复字符的代码
printf("结果字符串为:%s\n",str);
}
--
方法二:
char *delete_adjacent_char1(char *str)
{
if(str==NULL)
return NULL;

int i=0,j=0;
int len=strlen(str);
for(j=i+1;j<len;j++)
{
if(str[i]!=str[j])
str[++i]=str[j];
}
str[i+1]=0;

return str;
}
方法三:
char *delete_adjacent_char2(char *str)
{
if(str==NULL)
return NULL;

char *p=str;
char *q=p+1;
while(*q)
{
if(*p!=*q)
{
p++;
*p=*q;
q++;
}
else
{
q++;
}
}
*(p+1)=0;

return str;
}
方法四:
第2个回答  2008-03-26
1楼的方法不错,学习了.
但是输出按asc码排序了.

#include <stdio.h>

int main()
{
char s[256];
int i = 0, tmp[256] = {0};

printf("Enter the string :\n");
scanf("%s",s);

while(s[i] != '\0')
tmp[s[i++]] = 1;

puts("\nAfter sort and delete operation:");
for(i = 0; s[i]!='\0';i++)
if(tmp[s[i]])
{
tmp[s[i]]=0;
printf("%c", s[i]);
}

return 0;
}
第3个回答  2008-03-25
#include <stdio.h>

int main()
{
char s[256];
int i = 0, tmp[256] = {0};

printf("Enter the string :\n");
gets(s);

while(s[i] != '\0')
tmp[s[i++]] = 1;

puts("\nAfter sort and delete operation:");
for(i = 0; i < 256;i++)
if(tmp[i])
printf("%c", i);

return 0;
}

//自己把排序部分去掉。
第4个回答  2019-10-12
#include
<string>
#include
<iostream>
#include
<algorithm>
int
main()
{
std::string
str
=
"aabbcc";
std::cout
<<
"Before:
"
<<
str
<<
std::endl;
str.erase(std::unique(str.begin(),
str.end()),
str.end());
std::cout
<<
"After:
"
<<
str
<<
std::endl;
return
0;
}
第5个回答  2019-09-06
#include
<string>
#include
<iostream>
#include
<algorithm>
int
main()
{
std::string
str
=
"aabbcc";
std::cout
<<
"Before:
"
<<
str
<<
std::endl;
str.erase(std::unique(str.begin(),
str.end()),
str.end());
std::cout
<<
"After:
"
<<
str
<<
std::endl;
return
0;
}
相似回答