字符串---删除子串(1)
程序员文章站
2024-02-29 17:43:40
...
题目:编写一个函数,删除一个字符串的一部分。函数的原型如下:
int del_substr(char *str, char const *substr)
思路:先判断子串是否出现在源字符串中。如果未出现,返回0;如果出现,函数应该把str中位于该子串后面的所有字符复制到该子串的位置,然后函数返回1。如果子串多次出现在源字符串中,函数只删除第一次出现的子串。函数的第二个参数不容许改变。
在此思路下,很明显,需要额外的一个函数实现找出该子串的位置。
/*
**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;
}
本程序来自Kenneth A.Reek所著的《C和指针》,额外添加了main()主函数,所有程序在VS2017下调试通过。