c 中实现 replace 函数以及strstr两个函数的实现
时间:2010-08-31 来源:snailshen
#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;
}
#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;
}
相关阅读 更多 +