首页 > 代码库 > Implement strStr()

Implement strStr()

Implement strStr().

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


#include<stdio.h>
#include<string.h>

int strStr(char *haystack, char *needle) {
    int i,j,k;
    if(needle[0]=='\0') return 0;

    for(i=0;haystack[i]!='\0';i++){
        if(haystack[i]==needle[0]) {
            for(j=0,k=i;needle[j]!='\0';j++,k++){
                if(haystack[k]!=needle[j]) {
                    if(haystack[k]!='\0') break;
                    else return -1;
                }
            }
            if(needle[j]=='\0')
                return i;
        }
    }
    return -1;
}

void main(){
    printf("%d\n",strStr("abebef","bef"));
}




Implement strStr()