c 中实现 replace 函数以及strstr两个函数的实现

1669阅读 0评论2010-08-31 snailshen
分类:C/C++

#include
#include

const char * _strstr(const char *src, const char *needle)
{
const char *p1 = src;
const char *p2 = needle;

while (*src != '\0' && *needle != '\0')
{
if (*src++ != *needle++) {
needle = p2;
src = ++p1;   //从下一个字符开始搜索needle     
}
}

if (*needle == '\0')
return p1;

return NULL;
}


const char * strstr_ (const char *buf, const char *sub)
{
const char *bp;
const char *sp;

if (!*sub)
return buf;

while (*buf)
{
bp = buf;
sp = sub;
do
{
if (!*sp)
return buf;
} while (*bp++ == *sp++);
buf += 1;
}
return NULL;
}

void replace(const char *src, const char *s1,const char *s2, char *target)
{
const char *ss=src;
const char *p;

//p=strstr_(ss,s1);
p=_strstr(ss,s1);

if(p==NULL){
strcpy(target,src);
return;
}
while(p!=NULL) {

int n=p-ss;

strncat(target,ss,n);
strcat(target,s2);
ss=p+strlen(s1);

//p=strstr_(ss,s1);
p=_strstr(ss,s1);

}
strcat(target,ss);
}

int main( void )
{
char *a="asd12asd12";
printf("%d\n", (int)strlen(a));
char s[30]={0};
replace(a,"asd","ASDEF",s);
printf("%s\n",s);

return 0;

}
上一篇:位运算2
下一篇:位运算应用口诀和实例