bm是一種單模搜索算法
下面給出一般性的代碼,可運行
#include "stdio.h"
#include "string.h"
/*
基於二進制的bm搜索算法 區分大小寫 可以 混雜二進制不可見字符
*/
typedef int (*lookback)(int pos,int times); //bm中搜索回調函數 第一個參數爲匹配位置 ,第二個參數爲匹配次數
int InitBadWord(int bw[],const unsigned char substr[],const int len) //壞字表的初始化 區分大小寫
{
memset(bw,0,sizeof(int)*256);
int index=0;
for(index=0;index<256;index++)
{
bw[index]=len;
}
for(index=len-2;index>=0;index--)
{
bw[substr[index]]=len-1-index;
}
return 0;
}
int bmseek(const unsigned char *tarstr,const int tarlen,const unsigned char *sub,const int len,const int bw[],const lookback fun) // bm查找 跳字符查找
{
int times=0;
const unsigned char *strp=tarstr;
char endch=0;
int pos=0;
times++;
do
{
times++;
endch=tarstr[pos+len-1];
pos+=bw[endch];
strp=tarstr+pos;
if(pos+len>tarlen)
break;
if(memcmp(strp,sub,len)==0)
{
if(fun(pos,times)==0)
{
continue;
}
}
}while(1);
return 0;
}
int mylookback(const int pos, const int times)
{
printf("at %d times find pos %d\n",times,pos);
return 0;
}
int main()
{
int badword[256]; //申明 壞字表空間
char *substr="hihjkl"; //匹配字串
char *tarstr="abcdefghihjklmnopqrshihjhihjklkltuhihjklvwxyz"; //查找串
InitBadWord(badword,(unsigned char *)substr,strlen(substr)); //初始化壞字表
printf("ret=%d\n",
bmseek((unsigned char *)tarstr,strlen(tarstr),(unsigned char *)substr,strlen(substr),badword,mylookback)); //查找串
getchar();
return 0;
}