BF算法模式匹配

#include<iostream>
using namespace std;
int findstr(char* mainstr, char* sonstr);
int main() {

	char mainstr[100], sonstr[100];
	while (1)
	{
		cin >> mainstr >> sonstr;
		int set = findstr(mainstr, sonstr);
		if (set == -1)
			cout << "匹配失败" << endl;
		else
		cout <<sonstr<<"位于"<<mainstr<<"的第"<< set+1 <<"位"<< endl;
	}
	return 0;
}
int findstr(char* mainstr, char* sonstr)
{
	int mainlen = strlen(mainstr), sonlen = strlen(sonstr), i = 0, j = 0;
	while (i < mainlen && j < sonlen)
	{
		if (mainstr[i] == sonstr[j])
		{
			i++;
			j++;
		}
		else
		{
			i = i - j + 1;
			j = 0;
		}
	}
	if (i >= mainlen)
		return -1;
	else
		return i - j;
}
上一篇:【串】串的模式匹配算法(BF+KMP)(C语言)


下一篇:智能优化算法:饥饿游戏搜索算法-附代码