版权声明:转载必须注明出处,违者必究。 https://blog.csdn.net/qq_41856518/article/details/83821356
问题:给定两个字符串S和 T,在主串S中查找子串T,若查找成功,则返回子串在主串中的位置,否则返回0.
过程:从主串的第一个字符开始与子串的第一个字符开始比较,若相等,则继续比较两者的后续字符;若不相等,则从主串S的第二个字符和子串T的第一个字符比较,重复上述过程。若子串T的字符全部比较完毕,说明匹配成功。若主串S中的字符全部比较完毕,则匹配失败。
代码如下:
#include<iostream>
using namespace std;
const int maxsize=20;
int BF(char s[],char t[])
{
int index=0; //标记主串当前位置
int i=0,j=0;
while(s[i]!='\0'&&t[j]!='\0') //防止溢出
{
if(s[i]==t[j]){i++;j++;} //当前字符相同,比较下一位
else{index++;i=index;j=0;} //匹配失败,主串后移一位,子串从头开始
}
if(t[j]=='\0')return index+1;
else return 0;
}
int main()
{
char s[maxsize],t[maxsize];
while(cin>>s>>t)
{
int w=BF(s,t);
cout<<w<<endl;
}
}
运行结果:
改进后的算法叫KMP算法,感兴趣的小伙伴可以去看看:https://blog.csdn.net/qq_41856518/article/details/83832170