第八周项目5--计数的模式匹配

来源:互联网 发布:商家淘宝客推广 编辑:程序博客网 时间:2024/06/05 07:31
头文件SqString.h和源文件SqString.cpp代码详见顺序串算法库
[cpp] view plain copy 在CODE上查看代码片派生到我的代码片
#include <stdio.h>  
#include "sqString.h"  
int str_count(SqString s,SqString t)  
{  
    int i=0,j=0,count=0;  
    while (i<s.length && j<t.length)  
    {  
        if (s.data[i]==t.data[j])   //继续匹配下一个字符  
        {  
            i++;                //主串和子串依次匹配下一个字符  
            j++;  
        }  
        else                    //主串、子串指针回溯重新开始下一次匹配  
        {  
            i=i-j+1;            //主串从下一个位置开始匹配  
            j=0;                //子串从头开始匹配  
        }  
        //在BF算法中,没有下面的这一部分  
        //这里增加一个判断,可以“捕捉”到已经产生的匹配  
        if (j>=t.length)        //如果j已经达到了子串的长度,产生了一个匹配  
        {  
            count++;            //匹配次数加1  
            i=i-j+1;            //主串从下一个位置开始继续匹配  
            j=0;                //子串从头开始匹配  
        }  
    }  
    return(count);  
}  
int main()  
{  
    SqString s,t;  
    StrAssign(s,"accaccacacabcacbab");  
    StrAssign(t,"accac");  
    printf("s:");  
    DispStr(s);  
    printf("t:");  
    DispStr(t);  
    printf("%d\n",str_count(s,t));  
    return 0;  
}  
0 0
原创粉丝点击