#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);}