6-3 字符串 - 6. 查找子串(BF算法)* (10 分)

C语言标准函数库中包括 strstr 函数,在主串中查找子串。作为练习,我们自己编写一个功能与之相同的函数。

函数原型

// 查找子串
char* StrStr(const char *txt, const char *pat);

说明:txtpat 分别为主串和子串的起始地址。若查找成功,则函数值为子串在主串中首次出现的起始地址,否则函数值为NULL。

特别地,我们对C语言库函数strstr进行适当修改:若子串为空串,则没有意义,函数值规定为NULL。

裁判程序

#include <stdio.h>

// 查找子串
char* StrStr(const char *txt, const char *pat);

int main()
{
    char m[1024], s[1024], *p;
    gets(m);
    gets(s);
    p = StrStr(m, s);
    if (p)
    {
        printf("%d\n", p - m);
    }
    else
    {
        puts("Null");
    }
    return 0;
}

/* 你提交的代码将被嵌在这里 */

输入样例1

This is a pencil
is

输出样例1

2

输入样例2

This is a pencil
be

输出样例2

Null

 

代码:

char* StrStr(const char *txt, const char *pat)
{
      int i=0;
      int j=0,k=0;
      int m=strlen(txt);
      int n=strlen(pat);
      if(n==0)
        return NULL;
    while(i<m && j<n)
    {
        if(txt[i]==pat[j])   //继续匹配下一个字符
        {
            ++i;
            ++j;
        }
        else
        {
            i=i-j+1;  //主串从下一个位置开始匹配
            j=0;   //子串从头开始匹配
        }
    }
    if(j==n)
        return (char*)(txt+i-n);
    else
        return NULL;
}

 

 

 

  • 3
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值