1、
#include <stdio.h>
#include <string.h>
int delete(char *str,char *str_son,char *result_str)
{
int i = 0;
int str_son_len = strlen(str_son);
int str_len = strlen(str);
int count = 0;
if(strcmp(str,str_son) == 0) //两者相等,返回空;
{
result_str = NULL;
printf("error!\n");
return 0;
}
if(str_len < str_son_len || str_son == NULL) //子串大于主串,或子串为空,输出主串
{
while(*str != '\0')
{
*result_str = *str;
str++;
result_str++;
}
return 0;
}
while(*str != '\0')
{
while((*str != *str_son)&&( *str_son != '\0')) //两者不相等
{
*result_str = *str;
str ++;
result_str ++;
}
if(strncmp(str,str_son,str_son_len) != 0)
{
*result_str = *str;
str ++;
result_str ++;
}
else
{
count ++;
str += str_son_len;
}
}
*result_str = '\0';
return count;
}
int main()
{
char str[100];
char t[20];
char s[100];
printf("please input str:\n");
scanf("%s",str);
printf("please input son:\n");
scanf("%s",t);
delete(str,t,s);
printf("the result is :%s\n",s);
return 0;
}
2、
#include<string.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char a[20];
char *p=a;
char *q;
char *temp=(char*)malloc(sizeof(char)*20);
int len;
printf("please a:\n");
scanf("%s",a);
printf("please temp:\n");
scanf("%s",temp);
len = strlen(temp);
while((q = strstr(p,temp)) != NULL)
{
strcpy(q,q+len);
}
puts(p);
free(temp);
return 0;
}
3、
/*
src = "wangwangana" -> dest = "an" -> "wagwg"
*/
#include <stdio.h>
#include <stdlib.h>
static int delete(char *src,char *dest,char *result)
{
/* judge paramter */
if(src == NULL || dest == NULL)
{
return -1;
}
char *ptr = src; ////main string
char *str = dest; ////sub string
int count = 0;
int i = 0;
int flag;
while(*ptr != '\0')
{
count = 0; //////统计子串 和主串 相同的个数
flag = 0; ////判断子串和主串是否存在第一个字符相同
while(*str != '\0' && *ptr == *str)
{
flag = 1;
ptr++;
str++;
count++;
}
/* flag == 1 时,说明执行了上面的子串和主串*/
if(flag == 1)
{
if(*str == '\0')
{
str = dest; ///将子串str反回到原来dest
continue;
}
else
{
str = dest;
/* 将和主串不完全相同的子串部分 赋值给result*/
ptr = ptr - count;
for(i = 0; i < count;i++)
{
*result = *ptr;
ptr++;
result++;
}
continue;
}
}
/* 主串 和 子串 不一样的情况下 赋值给result*/
*result = *ptr;
ptr++;
result++;
}
*result = '\0';
return 0;
}
int main()
{
char *src;
char *dest;
char *result;
src = (char *)malloc(100*sizeof(char));
dest = (char *)malloc(100*sizeof(char));
result = (char *)malloc(100*sizeof(char));
printf("please input src string:\n");
scanf("%s",src);
printf("please input dest string:\n");
scanf("%s",dest);
delete(src,dest,result);
printf("result = %s\n",result);
free(src);
src = NULL;
free(dest);
dest = NULL;
free(result);
result = NULL;
return 0;
}