用C语言实现字符串搜索库函数strstr

用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;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值