字符串增强匹配
假设:有一个文本,想从里面搜索某些信息,
算法:horspool算法,
@浅夏沫若.code:
#include
#include
using namespace std;
string str1;
string str2;
int strlen1;
int strlen2;
//求移动长度
int movelength(char ch)
{
if (strlen2 == 1)
return strlen2;
if (strlen2 == 0)
return 0;
for (int i = strlen2 - 2; i >= 0; i--)
{
if (ch == str2[i])
return(strlen2 - 1 - i);
if ((ch != str2[i]) &&i == 0)
returnstrlen2;
}
}
//horspool算法进行匹配增强
bool horspoolMatching(string st1, string st2)
{
int i = strlen2 - 1;
while(i < strlen1)
{
for(int k=0;k
{
if (str1[i-k]!= str2[strlen2 - 1 - k])
{
i= i+movelength(str1[i]);
if(i >= strlen1)
returnfalse;
break;
#include
using namespace std;
string str1;
string str2;
int strlen1;
int strlen2;
//求移动长度
int movelength(char ch)
{
if (strlen2 == 1)
return strlen2;
if (strlen2 == 0)
return 0;
for (int i = strlen2 - 2; i >= 0; i--)
{
if (ch == str2[i])
return(strlen2 - 1 - i);
if ((ch != str2[i]) &&i == 0)
returnstrlen2;
}
}
//horspool算法进行匹配增强
bool horspoolMatching(string st1, string st2)
{
int i = strlen2 - 1;
while(i < strlen1)
{
for(int k=0;k
{
if (str1[i-k]!= str2[strlen2 - 1 - k])
{
i= i+movelength(str1[i]);
if(i >= strlen1)
returnfalse;
break;
cout<< str1[i - k] << "和" << str2[strlen2 - 1 - k]<< "未匹配上!" << endl;
}
if((str1[i-k] == str2[strlen2 - 1 - k]) && (k == strlen2 -1))
returntrue;
}
}
}
int main()
{
cout << "请输入文本:" << endl;
cin >> str1;
strlen1 = size(str1);
cout << "\n请输入模式:" << endl;
cin >> str2;
strlen2 = size(str2);
bool result = horspoolMatching(str1, str2);
cout << "\n匹配结果:";
if (result)
cout << "成功!\n";
else
cout << "失败!\n";
cout << endl;
return 0;
}
if((str1[i-k] == str2[strlen2 - 1 - k]) && (k == strlen2 -1))
returntrue;
}
}
}
int main()
{
cout << "请输入文本:" << endl;
cin >> str1;
strlen1 = size(str1);
cout << "\n请输入模式:" << endl;
cin >> str2;
strlen2 = size(str2);
bool result = horspoolMatching(str1, str2);
cout << "\n匹配结果:";
if (result)
cout << "成功!\n";
else
cout << "失败!\n";
cout << endl;
return 0;
}
分享: