c语言编写一段去除字符数组中重复的字符的程序

#include<stdio.h>
void main()
{
int i,j,p,q;
char a[8]={'a','b','b','c','d','a','v','b'};
for(i=0;i<8;i++)
{
for(j=i+1;j<=8;j++);
if(a[i]=a[j])
{
do
{a[j]=a[j+1];j++;}
while(j<=8);
}
}
puts(a[8]);
}
这是我写的,输出的是乱码。帮忙看下哪错了吧谢谢了
我还是喜欢按自己的思路来。就是把每个字符依次和后面的字符比较,如果相同,就把后面的每一个字符都用它之后的字符替换。
留香给改的基本正确了,不过运行的时候最后多出来一个b,我不知道是哪错了。再给看看吧。一楼的兄弟改的运行后输出除了本该输出的内容外还有一串乱码,三楼的我看不懂。
#include<stdio.h>
void main()
{
int i,j,p,q;
char a[9]={'a','b','b','c','d','a','v','b','\0'};
for(i=0;i<8;i++)
{
for(j=i+1;j<=8;j++)
if(a[i]==a[j])
{
do
{a[j]=a[j+1];j++;}
while(j<=8);
}
}
puts(a);
}

判断,标志输入的字符是否重复的,如下代码:

#include <stdio.h>
#include <vector>
struct detail
{
char c;
int exist;//标志位
};
std::vector<detail> statics;
int check(char c)
{
std::vector<detail>::iterator ite = statics.begin();
for (; ite != statics.end(); ite++)
{
if((*ite).c==c)return 0;//输入的字符已经存在
}
return 1;//输入的字符未存在
};
void main()
{
printf("请输入字符串:");
char c;
scanf("%c",&c);
while((int)c!=10)//获取用户输入
{
detail temp;
temp.c = c;
temp.exist = check(c);
statics.push_back(temp);
scanf("%c",&c);
}
std::vector<detail>::iterator ite = statics.begin();//打印非重复的字符
for (; ite != statics.end(); ite++)
{
if((*ite).exist)printf("%c",(*ite).c);
}
printf("\n");
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2010-12-14
帮你改好了,有几个小错误,第一个定义一个字符数组最好后面加上一个\0,内嵌套的for循环后面多了一个分号
#include<stdio.h>
void main()
{
int i,j,p,q;
char a[9]={'a','b','b','c','d','a','v','b','\0'};
for(i=0;i<8;i++)
{
for(j=i+1;j<=8;j++)
if(a[i]==a[j])
{
do
{a[j]=a[j+1];j++;}
while(j<=8);
}
}
puts(a);
}本回答被提问者采纳
第2个回答  2010-12-14
感觉你没有理清思路
你可以在定义一个数组b[8],然后把数组a中的字符一次放入b中,如果有重复则不放入
下面是代码,devc++上运行通过
#include<stdio.h>
main()
{
int i,j,n,flag;
char a[8]={'a','b','b','c','d','a','v','b'};
char b[8];
b[0]=a[0];

n=1;
for(i=1;i<8;i++)
{
flag=0;
for(j=0;j<n;j++)
if(b[j]==a[i]) {flag=1;break;}
if(flag==0){b[n]=a[i];n++;}
}
b[n]='\n';
puts(b);
getchar();
}本回答被网友采纳
第3个回答  2010-12-14
算了,不给你改了,我给你写一个吧
#include<iostream>
using namespace std;
int main()
{
char ch[9]={'a','b','b','c','d','a','v','b'};
int i,j;
int count = 0;
for (i = 0; i < 9;i ++)//不要忘了最后还有个'\0'
{
for (j = i+1;j<9;j++)
{
if(ch[i]==NULL)
{
continue;
}
if (ch[i]==ch[j])//有相同的元素的话,将其替换为后面的非空字符,并将最后一个非空字符置空
{
ch[j] = ch[8-count];
ch[8-count] = NULL;
j--;
count++;
}
}

}
ch[9-count] = '\0';
for (i=0;i<8-count;i++)
{
cout<<ch[i];
}
system("pause");
}
第4个回答  2010-12-14
#include<stdio.h>
void main()
{
int i,j,m=0;//m记录重复的字符数
char a[8]={'a','b','b','c','d','a','v','b'};
for(i=0;i<8;i++)
{
for(j=i+1;j<7;j++)//多了一个分号
{
if(a[i]==a[j])//应该是==
{
++m;
for(int k=0;k<7;++k)
{
a[k]=a[k+1];
}
}
}
}
a[8-m]='\0';
puts(a);
}