首页 > 代码库 > strstr实现

strstr实现

// strstr.c查找完全匹配的子字符串#include<stdio.h>#include<string.h>char *my_strstr(const char *s1,const char *s2){    const char *p=s1;    const int len=strlen(s2);    for(;(p=strchr(p,*s2))!=0;p++)    {        if(strncmp(p,s2,len)==0)        return(char *)p;    }    return (0);}char *my_strstr1(const char *s1, const char *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;}char *my_strstr2( 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;}int main(){    char *s="Golden Global View";    char *l="lob";    char *p;    //p=strstr(s,l);    //p=my_strstr(s,l);    p=my_strstr(s,l);    if(p)        printf("s=%s,p=%s\n",s,p);    else        printf("Not Found!\n");        {        char * rmlst = "ppp3.3/222.222.222.222";        char * cp1=NULL,* ipintf=NULL,*pubAddr=NULL;        cp1 = strstr(rmlst, "/");        if ( cp1 == NULL )            return;/*        *cp1 = ‘\0‘;        strncpy(ipintf, rmlst, cp1-rmlst);        strcpy(pubAddr, cp1+1);*/        printf("~~~~~~~~~~~,rmlst=%s,ipintf=%s,pubAddr=%s,cp1+1=%s\n\n\n\n", rmlst,ipintf,pubAddr,cp1+1);    }    getchar();            return 0;}

 

strstr实现