给定一篇文档和模式串,在文档中找出所有的模式串的位置。对文本中找出的模式串以不同颜色显示。
运行结果截图:


代码:
#include<iostream>
#include<fstream>
#include<string>
#include<windows.h>
using namespace std;
//next函数
void get_next(char* s, int* next)
{
int i = 0; //next数组的下标
int j = -1; //next值
next[0] = -1;
while (s[i] != '\0')
{
//如果不存在或者条件符合,可以得到next值
if (j == -1 || s[i] == s[j])
{
++i; ++j;
if (s[i] != s[j])//只有两者不相等的时候,才需要更换next值
next[i] = j;
else
next[i] = next[j];
}
else
{
j = next[j];
}
}
}
//KMP算法
int KMP(char* s, char* t, int pos)
{
int j = 0;
while (t[j++] != '\0');
int* next = new int[j - 1];
int length = j - 1; //串的长度
get_next(t, next);//调用函数,生成对应的next值
int i = pos - 1;//主串的起始位置
j = 0;//模式串的下标
while (s[i] != '\0' && j < length)
{
if (j == -1 || s[i] == t[j]) //考虑到第一个不相等的情况
{
++i; ++j;
}
else
{
j = next[j]; //如果不相等,则从next值开始下一次比较(模式串的右移)
}
}
if (t[j] == '\0' && j != -1)
{
return i - j;
}
else
{
return -1;
}
}
int main() {
//输入文件路径
string file_path;
cout << "输入文件路径:";
getline(cin, file_path);
//打开文件
ifstream ifs;
ifs.open(file_path, ios::in);
if (!ifs.is_open()) {
cout << "文件打开失败!" << endl;
return 0;
}
//读取文件内容到字符串
string str;
char c;
while ((c = ifs.get()) != EOF)
str += c;
ifs.close();
//输入查找的内容
string tmp;
cout << "输入要查找的内容:";
getline(cin, tmp);
//查找并输出
int left = -1, right = -1, n = 0;//left和right是模式串在字符串中的起止位置,n是字符串出现的次数
for (int i = 0; i < str.length(); i++) //遍历字符串中的每一个字符
{
if (i > right) //已经输出完上一个模式串后,更新left和right的位置,到下一个模式串
{
left = KMP((char*)str.data(), (char*)tmp.data(), i);
if (left >= 0)
{
n++;
right = left + tmp.length() - 1;
}
}
if (i >= left && i <= right) //如果是模式串中的字符,以红色显示
{
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_RED);
cout << str[i];
}
else //如果不是模式串中的字符,以白色显示
{
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 7);
cout << str[i];
}
}
cout << "\n\n" << n << "个结果\n";
return 0;
}
本文介绍了一种使用KMP算法在文本中查找模式串的方法,并通过不同颜色高亮显示匹配项。代码实现了next数组的计算及KMP匹配过程,用户可指定文档路径和搜索模式。

被折叠的 条评论
为什么被折叠?



