Implement strStr()

mplement strStr().

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

int strStr(char *haystack, char *needle) {

    if(haystack == NULL) return -1;
    if(needle == NULL) return 0;
    if(strlen(needle) > strlen(haystack)) return -1;
    int i,j;
    for(i = 0; i<=strlen(haystack)-strlen(needle); i++){
        for(j = 0; j<strlen(needle); j++)
        if(haystack[i+j] != needle[j]){
           break;
       }
       if(j == strlen(needle)) return i;
    } 
    return -1;
}

 

posted @ 2015-03-24 16:01  hongchun_z  阅读(93)  评论(0编辑  收藏  举报