function to delete part of a string

  Question: Write a function that deletes part of a string. The prototype of the function is as follows:

int  del_substr(char *str, char const *substr)

      Idea: First determine whether the substring appears in the source string. If it does not appear, it returns 0; if it does, the function should copy all characters in str after the substring to the position of the substring, and then the function returns 1. If the substring appears multiple times in the source string, the function removes only the first occurrence of the substring. The second parameter of the function cannot be changed.

       Under this line of thinking, it is obvious that an additional function implementation is needed to find the position of the substring.

/*
**If the string "substr" apears in "str",delete it.
*/
#include<stdio.h>
#define NULL 0
#define NUL '\0'
#define TRUE 1
#define FALSE 0

/*
** See if the substring begining 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) {
	/*
	**Keep looking while there are more characters in 'want'.
	**We fall out of the loop if we get a match.
	*/
	if (NULL == str || NULL == want)return NULL;
	while (NUL != *want )
		if (*str++ != *want++)
			return NULL;
	return str;
}

int
del_substr(char *str, char const *substr) {
	char *next =NULL;
	/*
	**Look through the string for the first occurence of the substring.
	*/
	while (NULL != *str) {
		next = match(str, substr);
		if (NULL != next)
			break;
		str++;
	}
	/*
	**If we reached the end of the string,
	**then the substring was not found
	*/
	if (NULL == *str)
		return false;
	/*
	**Delete the substring by copying the bytes after it
	**over the bytes of the substring itself.
	*/

	while (*str++ = *next++)
		;
	return TRUE;
}
int main() {
	char str[] = "I like lie it" ;
	char const* substr = "lie";
	if (del_substr(str, substr)) {
		printf("%s\n", str);
	}
	else
		printf("the substring doesn't apears in str");
	return 0;
}

      This program comes from "C and Pointers" by Kenneth A. Reek, with the addition of the main() main function, and all programs are debugged under VS2017.



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325358848&siteId=291194637