#include<stdio.h>
#include<assert.h>
#include <string.h>
char* my_strstr(const char* p1, const char* p2)
{
assert((p1 != NULL) && (p2 != NULL));//断言
char* s1;
char* s2;
char* arr = p1;
if (*p2 == '\0')//空串为任何非空串的子串
{
return (char*)p1;
}
while (*arr)//*s1='\0'退出循环,'\0'的值为0
{
s1 = arr;
s2 = p2;
while (*s1 && *s2 && (*s1 == *s2))//匹配找串,直到\0结束
{
s1++;
s2++;
}
if (*s2 == '\0')
{
return (char*)arr;//找到子串,返回找到位置的地址。
}
arr++;//没找到子串,arr就从下一个字符继续开始,s1再和s2匹配。
}
return NULL;//找不到,不存在
}
int main()
{
char* str1 = "abcd";
char* str2 = "cd";
char* ret=strstr(str1,str2);
printf("%s\n",ret);
printf("------------");
printf("\n%s", my_strstr(str1,str2));
return 0;
}
strstr()函数在库函数String.h中,作用是找到目的串中和源字符串匹配成功时的首地址。
例:在串abcde中找cd,找到位置是在第二个字符(下标为0~4)开始的。返回下标为2的地址。
至于为什么会打印cde,是因为%s,它会打印字符串,直到遇到\0结束。