28-简单-实现strStr()

在这里插入图片描述

int strStr(char * haystack, char * needle){
    int i = 0;
    int j = 0;
    int needle_len = 0; 

    if(0 == *needle) return 0;
    needle_len = strlen(needle);
    
    while(haystack[i]){
        if(haystack[i] != needle[j]){
            /* 不匹配则回到最开始匹配的地方,从下一个字符开始从新检测 */
            if(0 != j){
                i -= j;
                j = 0;
            }    
        }else{
            if((++j) >= needle_len){
                return i-needle_len+1;
            }
        }    
        i++;
    }
    return -1;
}

猜你喜欢

转载自blog.csdn.net/lala0903/article/details/107567473
28-