C语言字符串匹配函数

时间:2021-03-23 09:27:32

C语言字符串匹配函数,保存有需要时可以用:

 #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <time.h> /*
pattern:
pos:
*/ static int badShift[]; static int goodPostfixLastPos(const char *pattern,int pos)
{
#define _break(flag) if(flag){ break;} int flag = ;
int len = strlen(pattern);
int postFix_len = len - pos;
int postFix_position = pos;
int initStart = pos - postFix_len;
int last_start = ;
while(postFix_len)
{
last_start = (postFix_position == pos) ?initStart:;
int postFix_start = postFix_position;
for(;last_start>= && postFix_start<len;last_start++,postFix_start++)
{
flag = (pattern[last_start] == pattern[postFix_start]);
_break(!flag); } _break(flag);
if(initStart >= )
{
initStart--;
}
else
{
postFix_position++;
postFix_len--;
}
} return flag?last_start-:-;
} static int *calc_goodPostfixShift(const char *pattern,int *goodShift)
{
int len = strlen(pattern);
for(int i=;i<len;i++)
{
goodShift[i] = len - goodPostfixLastPos(pattern,i) - ;
} return goodShift;
} static int *clac_badcharShift(const char *ptrn)
{
int i;
int pLen = strlen(ptrn); for(i = ; i < ; i++)
{
*(badShift+i) = pLen;
} while(pLen != )
{
*(badShift+(unsigned char)*ptrn++) = --pLen;
} return badShift;
} int BMSearch(const char *str,const char *pattern)
{ int goodShift[strlen(pattern)];
int len1 = strlen(str);
int len2 = strlen(pattern); clac_badcharShift(pattern);
calc_goodPostfixShift(pattern,goodShift);
for(int i=len2 - ;i<len1;)
{
int start = i;
int pos_pattern = len2 - ;
for(;pos_pattern>=;pos_pattern--,start--)
{
if(str[start] != pattern[pos_pattern])
{
break;
}
}
if(pos_pattern < )
{
return start + ;
} if(pos_pattern == (len2 - ))
{
i += badShift[str[start]];
}
else
{
i += goodShift[pos_pattern + ];
}
} return -;
}