错误有三处:1.注释是用//不是用\\
2.int c;要改为int c=0;必须赋值为0.
3.buff赋完值之后必须加\0 ,作为结束符buff[c] = '\0';
#include
#include
class string{
char*s,*t; //储存两个字符串
char buff[50]; //储存公共字符串
public:
string(char*s1,char*t1){
s=new char[strlen(s1)+1];
t=new char[strlen(t1)+1];
strcpy(s,s1);
strcpy(t,t1);
}
~string(){delete s;delete t;}
int contain(char*str,char ch){ //判断str中是否包含字符ch
for( int j=0;j
return 0;
}
char*conp(char*str){ //删除str中重复的字符,只保留重复字符中的第一个字符并将结果返回
char*a,*b;
for(int i=0;i
a=str+j;
b=str+j+1;
while(*a++=*b++);
}
return str;
}
void fun()
{ //先调用函数conp(),删除字符串s中得重复字符,然后通过调用contain()一次判断s中得每一个字符是否包含在字符串t中,如果包含,则将该字符加入到数组buff中。
int c=0;
char d[50];
strcpy(d,s);
conp(d);
for(int i=0;i
if(contain(t,d[i]))
{
buff[c]=d[i];
c++;
}
}
buff[c] = '\0';
}
void print(){
cout<<"第一个字符串:"< cout<<"第二个字符串:"<
};
void main(){
char s[]={"xabcdabc"},t[]={"abcdefgab"};
string h(s,t);
h.fun();
h.print();
}
上面代码运行结果如下:
第一个字符串:xabcdabc
第二个字符串:abcdefgab
公共字符是:abcd
Press any key to continue
题外建议:
自己写的类不要和系统中的类名相同,可以加上My之类的头如MyString而不要使用string