《C和指针》第6章编程练习:
请编写一个函数,删除一个字符串的一部分,函数的原型如下:
int del_substr(char *str,char const *substr )
函数首先应该判断substr是否出现在str中,如果它并未出现,函数就返回0;如果出现,函数应该把str 中位于该子串后面的所有字符复制到该子串的位置,从而删除这个子串,然后函数返回1。如果substr多次出现在str中,函数只删除第1次出现的子串,函数的第二个参数绝不被修改。
要求:1不能使用任何操纵字符串的库函数
2 不能使用下标
/*
**删除一个字符串的一部分
*/
#include<stdio.h>
#include<string.h>
#define NUL '\0'
#define FALSE 0
#define TRUE 1
char *match( char *str, char *want);
int del_substr( char *str, char *substr );
int main()
{
char str[] = "ABCDEFG";
char *substr = "CDE";
del_substr(str, substr );
puts( str );
return 0;
}
/*
**为了清楚,单独写一个子函数实现判断两个字符串匹配
*/
char *match( char *str, char *want)
{
while( *want != NUL)
if( *str++ != *want++ )
return NULL;
return str;
}
/*
**删除子串函数
*/
int del_substr( char *str, char *substr )
{
char *next;
char *find = str;
/*
**保证被操作字符串不为空
**
*/
while( *find != NUL)
{
next = match( find, substr );
if( next != NULL)
break;
find++;
}
/*
**到达源字符串文件尾的时候,说明没有子串
*/
if( *find == NUL)
return FALSE;
/*
**被删除子串之后的字符复制操作
*/
while( *find++ = *next++ );
return TRUE;
}
参考了书给出的答案,但是遇到一个问题:
一开始,我把str定义为:char *str = "ABCDEFG",但是,执行到后面while( *find++ = *next++ );就出现问题,VC++提示
之后,了解到这样定义“ABCDEFG”是存储在文字常量区,所以,不允许修改。关于内存更详细的问题,
参考http://www.360doc.com/content/11/0521/17/5962329_118369832.shtml