strstr代码

来源:互联网 发布:美国大非农数据预测 编辑:程序博客网 时间:2024/05/22 07:05

strstr代码

#include<stdio.h>#include<string.h>#include<stdlib.h>char* my_strstr(char* s1, char* s2);void main(){    char* str1 = "abcdefcde";    char* str2 = "cde";    printf("the first %s of %s is:\n%s\n", str2, str1, my_strstr(str1, str2));}char* my_strstr(char * s1, char * s2){    int len2 = strlen(s2); //获得待查找串的长度    int tries; //比较的最大次数    int nomatch = 1; //没有匹配到子串,返回0    tries = strlen(s1) + 1 - len2; //此处说明最多只用比较这么多次    if (tries > 0)        while ((nomatch = strncmp(s1, s2, len2)) && tries--)            s1++;    if (nomatch)        return NULL;    else        return (char *)s1;}
0 0