【C庫函數】strstr實現

來源:互聯網
上載者:User
#include <stdio.h>#include <string.h>char *bxy_strstr(const char *s1, const char *s2) {int len2; if (!(len2 = strlen(s2))) {return (char *)s1; }for ( ;*s1; ++s1) { if (*s1==*s2 && strncmp( s1, s2, len2 ) == 0) {return (char *)s1;}} return NULL; } int main(void){   char *str1 = "Borland International. Welcome to nation.", *str2 = "nation", *ptr;   ptr = bxy_strstr(str1, str2);//返回str2在str1裡第一次出現的位置處的指標。   printf("The substring is: %s\n", ptr);   return 0;}

The substring is: national. Welcome to nation.
請按任意鍵繼續. . .The substring is: national. Welcome to nation.
請按任意鍵繼續. . .

#include <stdio.h>#include <assert.h>char *myStrstr(const char *str1, const char *str2){assert(str1 !=NULL && str2 != NULL);    if (str1 == str2)  //如果兩指標指向同一地址,直接返回str1    {        return (char *)str1;    }     char *s1, *s2;    while (*str1) //str1用於記錄找到子串的位置    {        s1 = (char *)str1;        s2 = (char *)str2;        //當str2中有字元與str1中的相同並且str1和str2都未至末尾時,迴圈        while ((*s1 == *s2) && *s1 && *s2)         {            s1++;            s2++;        }        //如果str2已經遍曆至末尾('/0')時,說明在str1中找到了子串str2       if ('\0' == *s2)        {            return (char *)str1; //返回找到的位置        }        str1++;     }    /* 尋找不成功,返回NULL */ return NULL;}void main(int argc,char *argv[]){    char *a ="aaHello worldHello!"; char *b = "Hello";    char *d= myStrstr(a,b);    printf("%s\n", d);}

 

#include <stdio.h>#include <assert.h>char *strstr_mf(const char *str1, const char *str2){assert(str1 !=NULL && str2 != NULL);//如果兩指標指向同一地址,直接返回str1    if (str1 == str2)      {        return (char *)str1;    }//str1用於記錄找到子串的位置    while (*str1)     {        char *s1 = (char *)str1;        char *s2 = (char *)str2;        //當str2中有字元與str1中的相同並且str1和str2都未至末尾時,迴圈        while ((*s1 == *s2) && *s1 && *s2)         {            s1++;            s2++;        }        //如果str2已經遍曆至末尾('/0')時,說明在str1中找到了子串str2       if ('\0' == *s2)        {            return (char *)str1; //返回找到的位置        }        str1++;     }return NULL;}void main(int argc,char *argv[]){    char *a ="asdHello world!"; char *b = "llo";    char *d= strstr_mf(a,b);   printf("%s\n", d);}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.