问题:
- /*
- * Copyright (c)2016,烟台大学计算机与控制工程学院
- * All rights reserved.
- * 文件名称:项目5.cpp
- * 作 者:PANCHUNYU
- * 完成日期:2016年10月21日
- * 版 本 号:v1.0
- *问题描述:采用顺序结构存储串,编写一个算法计算指定子串在一个字符串中出现的次数,如果该子串不出现则为0。
- 提示:无论BF模式匹配算法,还是KMP算法,都是在找到子串substr后就退出了。解决这个问题,要查找完整个字符串,并将出现的次数记下来。改造这两个算法吧。
- *输入描述:无
- *程序输出:测试数据
- *
代码:
头文件sqString.h代码:
- #include <stdio.h>
- #define MaxSize 100 //最多的字符个数
- typedef struct
- { char data[MaxSize]; //定义可容纳MaxSize个字符的空间
- int length; //标记当前实际串长
- } SqString;
- void StrAssign(SqString &s,char cstr[]); //字符串常量cstr赋给串s
- void StrCopy(SqString &s,SqString t); //串t复制给串s
- bool 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); //输出串
- #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;
- }
运行结果: