#include<stdio.h>
#include<string.h>
void squeeze(char s1[],char s2[]) // 定义squeeze函数,输入字符串s1和s2
{ // 将s1和s2进行对比,对应位置字母有重复的在s1
中删除后输出
int i=0,j=0; // 与K&R2-4中要求不一样,2-4要求s2中任意位置字母和s1任意位置字母重复都删除
char copy[strlen(s1)];
if(strlen(s1)<=strlen(s2)) // 需考虑s1和s2的长度,取短的进行遍历
{
while(s1[i]!='\0')
{
if(s1[i]!=s2[i])
{
copy[j++]=s1[i];
}
i++;
}
copy[j]='\0';
}
else
{
while(s2[i]!='\0')
{
if(s1[i]!=s2[i])
{
copy[j++]=s1[i];
}
i++;
}
while(s1[i]!='\0') // 若s2短,s2遍历后其余字符没有重复可能,将s1剩余部分原样复制
{
copy[j++]=s1[i++];
}
}
i=0;
while(copy[i]!='\0') //新的s1为copy,记得末尾补充一个结束符0
{
s1[i]=copy[i];
i++;
}
s1[i]='\0';
}
main()
{
char c[20],d[30];
int ch1,i=0,j=0;
int ch2;
while((ch1=getchar())!='\n')
{
c[i++]=ch1;
}
c[i]=0;
while((ch2=getchar())!='\n')
{
d[j++]=ch2;
}
d[i]=0;
printf("%s\n",c);
squeeze(c,d);
printf("%s",c);
getchar();
return 0;
}
输出结果:
c:beyondbanana
d:beyondabc
output:banana