函数实现
1.Copyright 1990 Software Development Systems, Inc.
char *strstr(const char *s1,const char *s2)
{
int len2;
if(!(len2=strlen(s2)))//此种情况下s2不能指向空,否则strlen无法测出长度,这条语句错误
return(char*)s1;
for(;*s1;++s1)
{
if(*s1==*s2 && strncmp(s1,s2,len2)==0)
return(char*)s1;
}
return NULL;
}
2.Copyright 1986 - 1999 IAR Systems. All rights reserved
char *strstr(constchar*s1,constchar*s2)
{
int n;
if(*s2)
{
while(*s1)
{
for(n=0;*(s1+n)==*(s2+n);n++)
{
if(!*(s2+n+1))
return(char*)s1;
}
s1++;
}
return NULL;
}
else
return (char*)s1;
}
3. GCC-4.8.0
char *strstr(const char *s1,const char *s2)
{
const char *p=s1;
const size_tlen=strlen(s2);
for(;(p=strchr(p,*s2))!=0;p++)
{
if(strncmp(p,s2,size_tlen)==0)
return (char*)p;
}
return(0);
}
4. 常用经典实现方法
char *strstr(const char *str1, const char *str2)
{
char *cp = (char*)str1;
char *s1, *s2;
if (!*str2)
return((char *)str1);
while (*cp)
{
s1 = cp;
s2 = (char *)str2;
while (*s1 && *s2 && !(*s1 - *s2))
s1++, s2++;
if (!*s2)
return(cp);
cp++;
}
return(NULL);
}
4的补充
char * strstr ( char *buf, char *sub)
{
if(!*sub)
return buf;
char *bp, *sp;
while (*buf)
{
bp = buf;
sp = sub;
do
{
if(!*sp)
return buf;
} while (*bp++ == *sp++);
buf++;
}
return 0;
}