《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