字符串匹配算法horspool

horspool()函数是引用别的作者成果,借用过来以供膜拜

#include

using namespace std;
int horspool(char *T, char *P);
int main(){
char *line = "learnopencv";
char *pat = "nop";
int s = horspool(line, pat);
cout << "We get shift= "< return 0;
}

int horspool(char *src, char *pattern){
int len1 = strlen(src);
int len2 = strlen(pattern);
int i, j, k;
char misch;
int mispos = 0;
for (i = 0; i <= len1 - len2;){
for (j = len2 - 1; j >= 0; --j){
if (src[i + j] != pattern[j]){
misch = src[i + j];//mismatch char
mispos = j;//position of mismatch
break;
}
if (j == 0)//匹配成功了
return i;
}

for (k = mispos - 1; k >= 0; k--){// 在模式串中寻找失配字符
if (pattern[k] == misch){
i += (mispos - k);
break;
}
if (k == 0){//找到最后,硬是没找着失配字符
i += (mispos + 1);
}
}
}
return -1;//最后的最后也没匹配成功,忧伤的返回-1。
}

你可能感兴趣的:(C++学习)