子字符串查找(暴力查找) -- C++实现


测试代码

//main.cpp
#include "Component.h"


int ViolentSearch(string pat,string txt,int iBegin = 0)
{
	int M = pat.length();
	int N = txt.length();

	for (int i = iBegin; i<= N-M; i++)
	{
		int j = 0;
		for (j = 0; j < M; j++)
		{
			if (txt.at(i+j) != pat.at(j))
				break;
		}

		if (j == M)
		{
			return i;
		}

	}

	return -1;
}

int main(int argc, char* argv[])
{
	string txt  ="qwhafhsjhfq87230878yqsdhfq9278r5278042yr5123qw8r098qthghasdfjhghajf08791232q9483r09q3uif123";
	int index1 = ViolentSearch("123",txt);
	cout << index1 << endl;
	cout << ViolentSearch("123",txt,index1+3) << endl;
}

 

暂无评论

注册用户登录后才能发表或者回复评论,请先登录 注册。