用C语言实现字符串搜索库函数strstr
#include <stdio.h>
int my_strstr(char *b1, char*b2)
{
int match_cnt = 0;
char *t1,*t2,*p1;
if (b1 == NULL || b2 == NULL) {
return -1;
}
p1 = b1;
while (*p1) {
t1 = p1;
t2 = b2;
do {
//printf("current t1=%c, t2=%c\n", *t1, *t2);
if ((*t1 == '\0' || *t2 == '\0')) {
//printf("cnt %d, %d\n", t2-b2, match_cnt);
if ((t2 - b2) == match_cnt) {
return (t1 - match_cnt - b1); // get position
} else {
break;
}
}
if (*t1++ == *t2++) {
++match_cnt;
} else {
match_cnt = 0;
}
} while (1);
++p1;
}
return -1;
}
int main(int argc, char *argv[])
{
int ret = 0;
char buf1[128], buf2[128];
printf("input buf1 and buf2\n");
scanf("%s\n%s",buf1,buf2);
printf("input is [%s],[%s]\n", buf1, buf2);
ret = my_strstr(buf1, buf2);
if (ret >= 0) {
printf("my_strstr position is %d\n", ret);
} else {
printf("my_strstr position not found\n");
}
return 0;
}