# 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); // returns the pointer at the position where str2 first appears in str1. Printf ("the substring is: % s \ n", PTR); Return 0 ;}
The substring is: national. Welcome to nation.
Press any key to continue... the substring is: national. Welcome to nation.
Press any key to continue...
# Include <stdio. h> # include <assert. h> char * mystrstr (const char * str1, const char * str2) {assert (str1! = NULL & str2! = NULL); If (str1 = str2) // if the two pointers point to the same address, str1 {return (char *) str1 ;}char * S1, * S2; while (* str1) // str1 is used to record the position of the substring {S1 = (char *) str1; S2 = (char *) str2; // when str2 contains the same characters as str1 and str1 and str1 and str2 are not at the end, the loop while (* S1 = * S2) & * S1 & * S2) {S1 ++; S2 ++ ;}/// if str2 has been traversed to the end ('/0, note that str2 if ('\ 0' = * S2) {return (char *) str1; // return the position} str1 ++} is found in str1 ;} /* If the search fails, null */return NULL;} void main (in T 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); // if the two pointers direct to the same address, str1 if (str1 = str2) {return (char *) str1;} is directly returned ;} // str1 is used to record the position of the substring while (* str1) {char * S1 = (char *) str1; char * S2 = (char *) str2; // when str2 contains the same characters as str1 and str1 and str1 and str2 are not at the end, the loop while (* S1 = * S2) & * S1 & * S2) {S1 ++; S2 ++ ;}/// if str2 has been traversed to the end ('/0, note that str2 if ('\ 0' = * S2) {return (char *) str1; // return the position} str1 ++} is found in str1 ;} return NULL;} void main (INT argc, char * argv []) {Cha R * a = "asdhello world! "; Char * B =" llo "; char * D = strstr_mf (a, B); printf (" % s \ n ", d );}