C++ KMP文本匹配

代码如下:

环境为VC

#include <iostream>
#include <algorithm>
#include <string>
#include <map>
#include <vector>
#include <cstring>
#include <utility>
#include <fstream>

using namespace std;

int* getNext(string p)
{
	int* next = new int[p.length()];
	next[0] = -1;       //第一个字符不匹配, i++,j++
	int j = 0;
	int k = -1;
	while (j < (int)p.length() - 1)
	{
		if (k == -1 || p[j] == p[k])
		{
			j++;
			k++;
			next[j] = k;
		}
		else
		{
			k = next[k];
		}
	}
	return next;
}

// KMP算法
int KMPMatcher(string T, string p)
{
	int i = 0;
	int j = 0;
	int* next = getNext(T);
	while (i < (int)T.length() && j < (int)p.length())
	{
		if (j == -1 || T[i] == p[j])
		{
			i++;
			j++;
		}
		else
		{
			j = next[j];
		}
	}
	if (j == (int)p.length())
	{
		return i - j;
	}
	return -1;
}

//分割字符串
vector<string> split(const string& str, const string& delim) {
	vector<string> res;
	if ("" == str) return res;
	//先将要切割的字符串从string类型转换为char*类型
	char * strs = new char[str.length() + 1];
	strcpy(strs, str.c_str());

	char * d = new char[delim.length() + 1];
	strcpy(d, delim.c_str());

	char *p = strtok(strs, d);
	while (p) {
		string s = p;  //分割得到的字符串转换为string类型
		res.push_back(s); //存入结果数组
		p = strtok(NULL, d);
	}
	return res;
}

int main() //生成通过关键字生成肢体动作指令
{   
	//关键词对话动作映射
	map<string, int> myMap;
	ifstream ous("dialog_action.txt");
	while (!ous.eof()) {
		string temp;
		ous >> temp;
		vector<string> tempstr = split(temp, "=");
		string key = tempstr[0].c_str();
		string value_1 = tempstr[1].c_str();
		int value = stoi(value_1); //string转int
		myMap.insert(make_pair(key, value)); //将字符串转换为键值对
	}

	map<string, int>::iterator it;
	
	for (it = myMap.begin(); it != myMap.end(); it++)
	{
		string T = sCmd;
                cout << "enter command:" << flush;
		getline(cin, sCmd);
		string p = it->first;
		if (KMPMatcher(T, p) >= 0) {
			it != myMap.end(); //跳出循环
			//cout << myMap[p] << endl;
			return myMap[p];
			break;
		}
	}
}
原文地址:https://www.cnblogs.com/spmt/p/11900228.html