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

问题及代码:

/*

copyright (t) 2016,烟台大学计算机学院

*All rights reserved.

*文件名称:1.cpp

*作者:常锐

*完成日期:2016年10月21日

*版本号:v1.0

*问题描述:采用顺序结构存储串,编写一个算法计算指定子串在一个字符串中出现的次数,如果该子串不出现则为0。

*输入描述:字符串(设为多组输入)

*程序输出:指定子串在一个字符串中出现的次数

*/

sqstring.h:

#include <stdio.h>
#define MaxSize 100
typedef struct                  //定义顺序串类型
{
    char data[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);                               //输出串

sqstring.cpp:

#include <stdio.h>
#include "sqstring.h"
int index(SqString s,SqString t)
{
    int i=0,j=0;
    int 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;
        }
        if(j>=t.length)                         //完成一次匹配后,次数+1
        {
            count++;
            i=i-j+1;                            //主串从下一位置开始匹配,子串从头开始匹配
            j=0;
        }
    }
    return count;
}
int main()
{
    SqString s1,s2;                             //s1为主串,s2为模式串
    char a[1000],b[1000];
    while(gets(a))
    {
        gets(b);
        StrAssign(s1,a);
        StrAssign(s2,b);
        printf("%d\n\n",index(s1,s2));
    }
    return 0;
}

main.cpp:

#include <stdio.h>
#include "sqstring.h"
int index(SqString s,SqString t)
{
    int i=0,j=0;
    int 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;
        }
        if(j>=t.length)
        {
            count++;
            i=i-j+1;
            j=0;
        }
    }
    return count;
}
int main()
{
    SqString s1,s2;                             //s1为主串,s2为模式串
    char a[1000],b[1000];
    while(gets(a))
    {
        gets(b);
        StrAssign(s1,a);
        StrAssign(s2,b);
        printf("%d\n\n",index(s1,s2));
    }
    return 0;
}

运行结果:


知识点总结:

        串的模式匹配

心得体会:

        通过此项目,我加深了对BF和KMP算法的理解与应用,能够打开思维,深入思考。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值