计数的模式匹配

问题:

[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. /*   
  2. * Copyright (c)2016,烟台大学计算机与控制工程学院   
  3. * All rights reserved.   
  4. * 文件名称:项目5.cpp   
  5. * 作    者:PANCHUNYU  
  6. * 完成日期:2016年10月21日   
  7. * 版 本 号:v1.0    
  8. *问题描述:采用顺序结构存储串,编写一个算法计算指定子串在一个字符串中出现的次数,如果该子串不出现则为0。  
  9.   
  10. 提示:无论BF模式匹配算法,还是KMP算法,都是在找到子串substr后就退出了。解决这个问题,要查找完整个字符串,并将出现的次数记下来。改造这两个算法吧。  
  11. *输入描述:无   
  12. *程序输出:测试数据   
  13. *  
代码:

头文件sqString.h代码:

[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. #include <stdio.h>  
  2. #define MaxSize 100             //最多的字符个数  
  3. typedef struct  
  4. {   char data[MaxSize];         //定义可容纳MaxSize个字符的空间  
  5.     int length;                 //标记当前实际串长  
  6. } SqString;  
  7.   
  8. void StrAssign(SqString &s,char cstr[]);    //字符串常量cstr赋给串s  
  9. void StrCopy(SqString &s,SqString t);   //串t复制给串s  
  10. bool StrEqual(SqString s,SqString t); //判串相等  
  11. int StrLength(SqString s);  //求串长  
  12. SqString Concat(SqString s,SqString t);  //串连接  
  13. SqString SubStr(SqString s,int i,int j); //求子串  
  14. SqString InsStr(SqString s1,int i,SqString s2); //串插入  
  15. SqString DelStr(SqString s,int i,int j) ;   //串删去  
  16. SqString RepStr(SqString s,int i,int j,SqString t);     //串替换  
  17. void DispStr(SqString s);   //输出串  

[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. #include <stdio.h>  
  2. #include "sqString.h"  
  3. int str_count(SqString s,SqString t)  
  4. {  
  5.     int i=0,j=0,count=0;  
  6.     while (i<s.length && j<t.length)  
  7.     {  
  8.         if (s.data[i]==t.data[j])   //继续匹配下一个字符  
  9.         {  
  10.             i++;                //主串和子串依次匹配下一个字符  
  11.             j++;  
  12.         }  
  13.         else                    //主串、子串指针回溯重新开始下一次匹配  
  14.         {  
  15.             i=i-j+1;            //主串从下一个位置开始匹配  
  16.             j=0;                //子串从头开始匹配  
  17.         }  
  18.         //在BF算法中,没有下面的这一部分  
  19.         //这里增加一个判断,可以“捕捉”到已经产生的匹配  
  20.         if (j>=t.length)        //如果j已经达到了子串的长度,产生了一个匹配  
  21.         {  
  22.             count++;            //匹配次数加1  
  23.             i=i-j+1;            //主串从下一个位置开始继续匹配  
  24.             j=0;                //子串从头开始匹配  
  25.         }  
  26.     }  
  27.     return(count);  
  28. }  
  29. int main()  
  30. {  
  31.     SqString s,t;  
  32.     StrAssign(s,"accaccacacabcacbab");  
  33.     StrAssign(t,"accac");  
  34.     printf("s:");  
  35.     DispStr(s);  
  36.     printf("t:");  
  37.     DispStr(t);  
  38.     printf("%d\n",str_count(s,t));  
  39.     return 0;  
  40. }  

运行结果:
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值