请编写一个函数,删除一个字符串的一部分

来源:百度知道 编辑:UC知道 时间:2024/06/15 08:30:30
请编写一个函数,删除一个字符串的一部分,函数的原型如下:
int del_substr(char str[],char const substr[] )
函数首先应该判断substr是否出现在str中,如果它并未出现,函数就返回0;如果出现,函数应该把str 中位于该子串后面的所有字符复制到该子串的位置,从而删除这个子串,然后函数返回1。如果substr多次出现在str中,函数只删除第1次出现的子串,函数的第二个参数绝不被修改。

#include<stdio.h>
#define true 1
#define false 0
#define NUL '\0'

int main()
{
int del_substr(char *,char * );
char *match(char * ,char * );
char s1[] = "abcdefghi";
char s2[]= "cde";
int a = del_substr(s1,s2);
printf("%d\n",a);
printf("%s\n",s1);

}

int
del_substr(char *str,char *substr )
{
char *next;
while(*str!=NUL)
{
next = match(str,substr);
if (next!=NULL)
break;
str++;
}
if (*str==NUL)
return false;
while(*str!='\0'){*str++ = *next++;}
return true;
}

char *
match(char *str,char *want)
{
char *sp;char *cp;cp=str;sp=want;
while (*sp!=NUL)
{
if (*sp++!=*cp++)
return NULL;}
return cp;

}