改进一下昨天的代码,
int strstr_basic(char* str, char* pattern)
{
char *s = NULL;
char *p = NULL;
int i = 0;
int lenStr = 0;
int lenPattern = 0;
if (NULL == str || NULL == pattern)
{
return -1;
}
p = str;
while ('/0' != p)
{
lenStr++;
p++;
}
p = pattern;
while ('/0' != p)
{
lenPattern++;
p++;
}
if (lenStr < lenPattern)
{
return -1;
}
s = str;
p = pattern;
/* 逐个比较使用指针p++,定位使用指针加位置索引i,逻辑就清晰了 */
while (i <= lenStr - lenPattern)
{
/* s,p 负责比较,i负责定位 */
if (*s++ == *p++)
{
/* p的字符串被全部匹配 */
if ('/0' == p)
{
return i;
}
}
else
{
i++;
s = str + i;
p = pattern;
}
}
return -1;
}