int strStr(string haystack, string needle)
{
if (needle.empty())
return 0;
if (haystack.empty() && !needle.empty())
return -1;
const char *hp = haystack.c_str();
const char *np = needle.c_str();
while ( *hp != '\0')
{
if (*hp != *np)
{
hp++;
}
else
{
const char *m = hp;
const char *n = np;
while (*m == *n && *m != '\0' && *n != '\0')
{
m++;
n++;
}
if (*n == '\0') // 找到
return (hp-haystack.c_str()); // 返回匹配位置
if (*m == '\0') // 不匹配
return -1;
hp++; // 当前指针指向的字符串不匹配,向后继续查找
}
}
return -1;
}
测试用例:
haystack: mississippi
needle: issip
return: 4