23,121
社区成员
发帖
与我相关
我的任务
分享
#include <stdlib.h>
#include <stdio.h>
/*
** If the string "substr" appears in "str", delete it.
*/
//#define NULL 0 /* null pointer */
//#define NUL ’\0’ /* null byte */
#define TRUE 1
#define FALSE 0
/*
** See if the substring beginning at ’str’ matches the string ’want’. If
** so, return a pointer to the first character in ’str’ after the match.
*/
char *match (char *str, char const *want)
{
while (*want != '\0') {
if (*str++ != *want++) {
return NULL;
}
}
return str;
}
int del_substr (char *str, char const *substr)
{
char *next = NULL;
char *res = str;
/*
** Look through the string for the first occurrence of the substring.
*/
while( *str != '\0' ){
next = match( str, substr );
if( next != NULL )
break;
str++;
}
printf("##next: %s\n", next);
printf("##str: %s\n", str);
/*
** If we reached the end of the string, then the substring was not
** found.
*/
if( *str == '\0' )
return FALSE;
/*
** Delete the substring by copying the bytes after it over the bytes of
** the substring itself.
*/
while(*next != '\0'){
(*str) = (*next);
printf("##str: %s\n", str);
printf("##next: %s\n", next);
str++;
next++;
}
*str = '\0';
printf("after del_substr result: %s\n", res);
return TRUE;
}
int main()
{
char *str = "ABCDEFG";
char const *sub_str1 = "FGH";
char const *sub_str2 = "DE";
int res = -1;
res = del_substr(str, sub_str2);
// printf("the resust is %s\n", str);
printf("the res is %d\n", res);
return res;
}
38 printf("##next: %s\n", next);
(gdb)
##next: FG
39 printf("##str: %s\n", str);
(gdb)
##str: DEFG
44 if( *str == '\0' )
(gdb)
50 while(*next != '\0'){
(gdb)
51 (*str) = (*next);
(gdb)
Program received signal SIGSEGV, Segmentation fault.
0x0804849f in del_substr (str=0x8048667 "DEFG", substr=0x8048670 "DE")
at del_substr.c:51
51 (*str) = (*next);
(gdb)