BF算法类似strstr函数,假设str1是待查找的字符串,str2是一个子串,我们要从str1中查找是否存在str1子串,若有则返回str2在str1中首次出现第一个字符的地址。否则返回NULL。
#include<stdio.h>
#include<assert.h>
#include<string.h>
int BF(char* str1,char* str2)
{
assert(str1!=NULL&&str2!=NULL);//这里要引用头文件
if(str1==NULL||str2==NULL)//NULL跟"\0"在这里可以替换
{
return -1;
}
int lenstr1=strlen(str1);
int lenstr2=strlen(str2);
int i=0;
int j=0;
while(i<lenstr1&&j<lenstr2)
{
if(str1[i]==str2[j])
{
i++;
j++;
}
else
{
i=i-j+1;//这里是关键,需要结合图理解。这是当移动的时候字符不同时str1地址需要回到的位置
j=0;//这时j需要返回str2开头
}
if(j>=lenstr2)
{
return i-j;
}
}
return -1;
}
int main()
{
printf("%d\n",BF("ababcabcd","abcd"));
printf("%d\n",BF("ababcabcd","ab"));
printf("%d\n",BF("ababcabcd","abcde"));
return 0;
}
str1:a b a b c a b c d
地址0 1 2 3 4 5 6 7 8
i(0)
str2:a b c d
地址0 1 2 3
j(0)
因为这时str1[i]等于str2[j],所以i++,j++
str1:a b a b c a b c d
0 1 2 3 4 5 6 7 8
i
str2:a b c d
0 1 2 3
j
这时仍然一样继续向后移,下一步不相等是关键
str1:a b a b c a b c d
0 1 2 3 4 5 6 7 8
i
str2:a b c d
0 1 2 3
j
这时i对应的字符不等于j对应的字符,这时str2的j需要重新赋值0,又重头遍历(j较好理解)
对于i它需要重新变为i-j+1,举例,如下
str1:a b a b c a b c d
0 1 2 3 4 5 6 7 8
i
str2:a b c d
0 1 2 3
j
这时a不等于c,i需要从上一次的地址的下一个地址1开始再遍历,i=i-j+1,i=2-2+1=1处重新开始
依次类推
运行结果:(5和0表示找到符合条件的str1在str2的起始地址,-1表示未找到)