Implement strStr()

来源:互联网 发布:java项目开发四个步骤 编辑:程序博客网 时间:2024/06/09 19:38

即:自己实现strstr()函数
Implement strStr().

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

解题思路:
求出两个函数的长度差值,即返回值index的取值范围

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

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

}

0 0