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

来源:互联网 发布:少儿电脑绘画软件 编辑:程序博客网 时间:2024/04/30 11:53

问题及代码:

/*  *Copyright(c) 2015, 烟台大学计算机学院  *All rights reserved.  *文件名称:计数的模式匹配.cpp  *作    者:杜文文  *完成日期:2015年 10月 30日   *问题描述:采用顺序结构存储串,编写一个算法计算指定子串在一个字符串中出现的次数,如果该子串不出现则为0。            提示:无论BF模式匹配算法,还是KMP算法,都是在找到子串substr后就退出了。      解决这个问题,要查找完整个字符串,并将出现的次数记下来。*/


SqString.h

#ifndef SqString_H_INCLUDED#define SqString_H_INCLUDED#define MaxSize 100             //最多的字符个数typedef struct{   char data[MaxSize];         //定义可容纳MaxSize个字符的空间    int length;                 //标记当前实际串长} SqString;void StrAssign(SqString &s,char cstr[]);    //字符串常量cstr赋给串svoid StrCopy(SqString &s,SqString t);   //串t复制给串sbool StrEqual(SqString s,SqString t); //判串相等int StrLength(SqString s);  //求串长SqString Concat(SqString s,SqString t);  //串连接SqString SubStr(SqString s,int i,int j); //求子串SqString InsStr(SqString s1,int i,SqString s2); //串插入SqString DelStr(SqString s,int i,int j) ;   //串删去SqString RepStr(SqString s,int i,int j,SqString t);     //串替换void DispStr(SqString s);   //输出串#endif // SqString_H_INCLUDED


 

SqString.cpp

#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);}void StrAssign(SqString &s,char cstr[]) //s为引用型参数{   int i;    for (i=0;cstr[i]!='\0';i++)        s.data[i]=cstr[i];    s.length=i;}void DispStr(SqString s){   int i;    if (s.length>0)    {   for (i=0;i<s.length;i++)            printf("%c",s.data[i]);        printf("\n");    }}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