1、sunday算法原理
在匹配过程中,文本串首先按从左向右进行逐个匹配,当发现有不匹配的字符时,当前匹配的位置就跳过尽可能大的步长,再进行下一轮的匹配,从而达到提高匹配效率的目的。Sunday算法匹配失败时,判断文本串中参加匹配的最末位字符的下一位字符是否在模式串中出现。如果未出现,跳转步长为模式串长度加1;如果出现,其跳转步长为模式串中最右端的该字符到末尾的距离加1。
文本串:substring searching algorithm模式串:search
简而言之,sunday算法核心操作如下(i为文本串游标,j为模式串游标):
1)如果出现:i的位置 = 以 找到的字符下标 为基点,挪动到相对于匹配串的起始位置。;
2)如果未出现:i的位置 = 文本串中参加匹配的最末位字符的下一位 的下一位
2、C代码实现
/*************************************************************************
author:tmw
date:2018-2-26
**************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/**查找某个字符在模式串中是否存在(从后往前寻找),存在则返回所在模式串的下标,不存在则返回-1**/
int findIndex(char* match_str , char ch)
{
int i;
//从后往前寻找
for( i=strlen(match_str)-1;i>0;i--)
if(match_str[i] == ch)
return i;
return -1;
}
/**Sunday算法**/
int strMatch_Sunday(char* text_str , char* match_str)
{
int i=0;
int j=0;
while( i < strlen(text_str) )
{
if( text_str[i] == match_str[j] )
{
i++;
j++;
if( j == strlen(match_str) )
{
printf("找到匹配串! 匹配位置为:[%d ~ %d]\n",i-strlen(match_str),i-1);
return 0;
}
}
else
{
int temp = i+strlen(match_str)-j;
//判断文本串中参加匹配的最末位字符的下一位字符是否在模式串中出现
int index = findIndex(match_str,text_str[temp]);
if( index != -1)
// 如果出现:i的位置 = 以 找到的字符下标 为基点,挪动到相对于匹配串的起始位置。
i = temp - index;
else
// 如果未出现:i的位置 = 文本串中参加匹配的最末位字符的下一位 的下一位
i = temp + 1;
j=0;
}
}
printf("未找到匹配串...\n");
return 0;
}
3、测试代码及测试结果
int main()
{
printf("测试代码\n");
char text_str1[20] = "substring searching";
char match_str1[7] = "search";
printf("文本串为:%s\n",text_str1);
printf("匹配串为:%s\n",match_str1);
strMatch_Sunday(text_str1,match_str1);
printf("\n");
char text_str2[20] = "hello world lalala";
char match_str2[7] = "aaa";
printf("文本串为:%s\n",text_str2);
printf("匹配串为:%s\n",match_str2);
strMatch_Sunday(text_str2,match_str2);
return 0;
}