方法一:比较小白的写法
#include <stdio.h>
#include <assert.h>
const char *strstr(const char *src, const char *sub)
{
const char *b;
const char *a;
while (*src)
{
if (*src == *sub)
{
a = src;
b = sub;
while (*b)
{
a++;
b++;
if (!*b)
{
return src;
}
if (*a != *b)
{
src++;
break;
}
}
}
else
{
src++;
}
}
return NULL;
}
int main(void)
{
char bp[] = "kjfdhsgkjsdhgksdhgfiuuirewk";
char sq[] = "uu";
const char *r = strstr(bp,sq);
printf("r:%s\n", r);
}
方法二:高级一点点的写法
#include <stdio.h>
#include <assert.h>
const char *strstr(const char *src, const char *sub)
{
const char *bp;
const char *sp;
if (!src || !sub)
{
return src;
}
/* 遍历src字符串 */
while (*src)
{
/* 用来遍历子串 */
bp = src;
sp = sub;
while ((*bp++ == *sp))
{
sp++;
}
//do
if (!*sp) /*到了sub的结束位置,返回src位置 */
{
return src;
}
src++;
}
return NULL;
}
int main(void)
{
char bp[] = "ajfdhjhss";
char sq[] = "jh";
const char *offset = strstr(bp, sq);
if (offset != NULL)
{
printf("offset=%s\n", offset);
}
else
{
printf("not find\n");
}
return 0;
}