输入2个字符串S1和S2,要求删除字符串S1中出现的所有子串S2,即结果字符串中不能包含S2。
输入格式:
输入在2行中分别给出不超过80个字符长度的、以回车结束的2个非空字符串,对应S1和S2。
输出格式:
在一行中输出删除字符串S1中出现的所有子串S2后的结果字符串。
输入样例:
Tomcat is a male ccatat
cat
结尾无空行
输出样例:
Tom is a male
结尾无空行
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
int check(char s3[81],char s2[81]) //用于检测字符串中是否含有s2
{
int L_3 = strlen(s3), L_2 = strlen(s2);
int i = 0;
while(i <= L_3 - L_2)
{
if(!strncmp(s2,s3 + i,L_2)) //如果检测到含有s2则返回0
{
return 0;
}
i++;
}
return 1;
}
int main()
{
char s1[81],s2[81],s3[81]; //s3用来存储s1删除s2后的字符串
scanf("%[^\n]",&s1);
getchar(); //将回车符读取
scanf("%[^\n]",&s2);
while(1)
{
int L_1 = strlen(s1),L_2 = strlen(s2); //保存s1和s2的长度
int i,j = 0;
for(i = 0; i < L_1; i++)
{
if(!strncmp(s2,s1 + i,L_2) && i <= (L_1 - L_2)) //如果找到了一样的就跳过
{
i += L_2;
}
s3[j++] = s1[i];
}
s3[j] = '\0';
if(check(s3,s2)) //如果s3中已经不包含s2了,就停止
{
break;
}
else
{
strcpy(s1,s3);
strcpy(s3,"");
}
}
printf("%s",s3);
return 0;
}