-
#include
-
-
const char *my_strstr(const char *str, const char *sub_str)
-
{
-
for(int i = 0; str[i] != '\0'; i++)
-
{
-
int tem = i;
-
int j = 0;
-
while(str[i++] == sub_str[j++])
-
{
-
if(sub_str[j] == '\0')
-
{
-
return &str[tem];
-
}
-
}
-
i = tem;
-
}
-
-
return NULL;
-
}
-
-
int main()
-
{
-
char *s = "1233345hello";
-
char *sub = "345";
-
printf("%s\n", my_strstr(s, sub));
-
return 0;
-
}
-
int strstr(char *string, char *substring)
-
{
-
if (string == NULL || substring == NULL)
-
return -1;
-
-
int lenstr = strlen(string);
-
int lensub = strlen(substring);
-
-
if (lenstr < lensub)
-
return -1;
-
-
int len = lenstr - lensub;
-
for (int i = 0; i <= len; i++) //复杂度为 O(m*n)
-
{
-
for (int j = 0; j < lensub; j++)
-
{
-
if (string[i+j] != substring[j])
-
break;
-
}
-
if (j == lensub)
-
return i + 1;
-
}
-
return -1;
-
}
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/29012686/viewspace-1145082/
,如需转载,请注明出处,否则将追究法律责任。