zj@zj:~/C_parm/string/own_str/strstr$ cat strstr.c /*
*The strstr() function finds the first occurrence of the substring
*needle in the string haystack. The terminating '\0' characters
*are not compared.
*strstr.c
*/
int main() { char* str1 ="abcdefcde"; char* str2 ="cde"; printf("the first ocu %s of %s is:\n%s\n",str2,str1,my_strstr(str1,str2)); exit(EXIT_SUCCESS); }
char* my_strstr(constchar* s1,constchar* s2) { int len2 =strlen(s2);/* 获得待查找串的长度*/ int tries;/* maximum number of comparisons */ int nomatch = 1;/* set to 0 if match is found */
tries =strlen(s1)+ 1 - len2;/*此处说明最多只用比较这么多次,*/ if(tries > 0) while(( nomatch =strncmp(s1, s2, len2))&& tries--)
s1++; if(nomatch) returnNULL; else return(char*) s1;/* cast const away */ }
zj@zj:~/C_parm/string/own_str/strstr$./strstr
the first ocu cde of abcdefcde is:
cdefcde