字符串普通模式匹配和KMP模式匹配[面相对象喽]

学校的课程设计,本来可以简简单单的描述一下就好了。但是这学期不是面向对象了吗?那么为什么不用面向对象来画蛇添足一下呢?笨笨可可捅鼓了到很晚,贴出来做个纪念。

程序说明:

实现对输入的两个字符串,一个主串一个子串...进行模式匹配.check是普通模式匹配,kmpcheck是KMP算法模式匹配.所以会有两个输出结果,理论上两个结果应该是一致的,实际操作中也是一样...反正我试了几组都没出错...程序简单,没写注释,懒一把.

VC++ 6.0下测试通过

源代码:

//CheckString.h

class CheckString
{
 char key;
public:
 char s[20];
 int len;
 int viewhead;
 int viewend;
 void input();
 void check(const CheckString &substring);
 void kmpcheck(const CheckString &substring);
 void viewnext();
};

//main.cpp

#include <iostream.h>
#include "CheckString.h"

void main()
{
 CheckString mainstring;
 CheckString substring;
 cout<<"输入主串:"<<endl;
 mainstring.input();
 cout<<"输入子串:"<<endl;
 substring.input();
 cout<<"普通模式匹配算法开始:"<<endl;
 mainstring.check(substring);
 cout<<"KMP模式匹配算法开始:"<<endl;
 mainstring.kmpcheck(substring);
}

//CheckString.cpp

#include<iostream.h>
#include<stdio.h>
#include "CheckString.h"
void CheckString::input()

 len=0;
 while((key=getchar())!='/n')
 {
  s[++len]=key;
 }
}

void CheckString::check(const CheckString &substring)
{
 int i=1,j=1;
 while(i<=len)
 {
  if(s[i++]==substring.s[j])
  {
   j++;
   if(j>substring.len)break;
  }
  else
  {
   j=1;
  }
 }
 if(j>substring.len)
 {
  viewhead=i-substring.len;
  viewend=viewhead+substring.len-1;
  cout<<"满足匹配起始位置:"<<viewhead<<endl;
  cout<<"满足匹配结束位置:"<<viewend<<endl<<endl;
 }
 else
  cout<<"没有一样的啊!!"<<endl<<endl;
}

void CheckString::kmpcheck(const CheckString &substring)
{
 int i=1,j=1;
 int k=0;
 int next[20];
 next[1]=0;
 while(j<substring.len)
  if((k==0)||(substring.s[j]==substring.s[k]))
  {
   j++;
   k++;
   next[j]=k;
  }
  else
   k=next[k];
 cout<<"输出next[]数组:";
 for(i=1;i<=substring.len;i++)
  cout<<next[i];
 cout<<endl;
 i=1;j=1;
 while((i<=len)&&(j<=substring.len))
  if((j==0)||(s[i]==substring.s[j]))
  {
   i++;
   j++;
  }
  else
   j=next[j];
 if(j>substring.len)
 {
  viewhead=i-substring.len;
  viewend=viewhead+substring.len-1;
  cout<<"满足匹配起始位置:"<<viewhead<<endl;
  cout<<"满足匹配结束位置:"<<viewend<<endl<<endl;
 }
 else
  cout<<"没有一样的啊!!"<<endl<<endl;
}

完事儿。^_^

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值