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

2010-03-26 22:48
#include<string.h>
#include<stdio.h>

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;

你可能感兴趣的:(c 中实现 replace 函数以及strstr两个函数的实现)