"C and Pointers", chapter 6th programming Exercises:
Write a function that deletes a part of a string, and the function is prototyped as follows: the int del_substr (char *str,char const *SUBSTR) function should first determine whether substr appears in Str, and if it does not appear, the function returns 0 If it appears, the function should copy all the characters that follow the substring in STR to the location of the substring, thereby deleting the substring and returning the function to 1. If SUBSTR is present in Str multiple times, the function removes only the 1th occurrence of the substring, and the second parameter of the function is never modified. Requirement: 1 cannot use any library function that manipulates a string 2 cannot use subscript
Behind the source code and comments
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int Del_substr (char *str,char const *SUBSTR);//function declaration
int main ()
{
int ret = 0;
Char str[20];
Char substr[20];
printf ("Please input str substr:\n");
scanf ("%s%*c", str);
scanf ("%s", substr);
printf ("str:%s,substr:%s\n", str,substr);
ret = DEL_SUBSTR (STR,SUBSTR);
printf ("The Change str:%s\n", str);
printf ("%d\n", ret);
return 0;
}
/*
* * Complete your own first count character comparison function, same as return 0
*/
int my_strncmp (const char *s1,const char *s2,int count)
{
const char *C1 = S1;
const char *C2 = s2;
while (--count&& (*c1 = = *C2))
{
C1 + +;
C2 + +;
}
return *C1-*c2;
}
/*
* * Complete its own detection string length function, return string length
*/
int My_strlen (const char *STR)
{
const char *S1 = str;
for (S1 = str;*s1! = '); s1++)
{
;
}
return s1-str;
}
/*
* * Delete string function, successfully return 1,STR to delete the first occurrence of substr; failure returns 0,STR unchanged
*/
int Del_substr (char *str,char const *SUBSTR)
{
int flag = 0;//controls the variable that is deleted only once
char *ptr = str;
char *src = str;
int len = My_strlen (substr);
while (*src! = ')
{
if (flag = = 0&&MY_STRNCMP (src,substr,len) = = 0)
{
src = src + len;//match succeeds, Src point to post-move Len
flag = 1;
}
*ptr++ = *src++;//The character that the SRC points to assigned to the PTR point
}
*ptr = ' + ';
str = ptr;//assigns the modified string to Str.
if (flag = = 1)//If the string has been altered once, return 1
{
return 1;
}
return 0;
}
Remove part of a string