6-5 字符串 - 6. 查找子串(BF算法)* (12 分)
C语言标准函数库中包括 strstr 函数,在主串中查找子串。作为练习,我们自己编写一个功能与之相同的函数。
函数原型
// 查找子串
char* StrStr(const char *txt, const char *pat);
说明:txt 和 pat 分别为主串和子串的起始地址。若查找成功,则函数值为子串在主串中首次出现的起始地址,否则函数值为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 §
{
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)
{
char *p=(char *)txt;
char *q=(char *)pat;
int l1=0,l2=0,i=0,j=0;
while(txt[l1]!='\0') l1++;
while(pat[l2]!='\0') l2++;
i=0,j=0;
if(l2<=0)
return NULL;
while(i<l1&&j<l2)
{
if(p[i]==q[j])
{
i++;
j++;
}
else
{j=0;
i=i-j+1;
}
}
if(j>=l2)
return p+(i-l2);
return NULL;
}