字符串匹配--sunday算法

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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值