串的模式匹配算法(非kmp)

//串的模式匹配算法(非kmp)

//求子串位置的定位函数index(***,***,int **)

#include <iostream>
#include <string>

using namespace std;

int index(const char *res, const char *str, int position)
{

 int i=position;
 int j=0;
 int lengthRes=strlen(res);
 int lengthStr=strlen(str);
 while(i<=lengthRes && j<=lengthStr) 
 {
  if(res[i]==str[j])
  {
   // go on matching
   ++i;  
   ++j;
  }
  else if( j == lengthStr )
   return i-lengthStr;
  else
  {
   //set the point back to next starting character and for further match.
   i=i-j+2;
   j=1;
  }
 }
 return 0;
}


int main()
{
  char *res="abcdefghijklmnopqrstuvwxyz"; 
  char *str="fg";
  int position = -1;  //want to specify this variable, use cin....
  int index_=0;
  index_ = index(res, str, position);
  cout << index_<<endl;
  return 0;
}

 

改进了一下, 主要是针对在原字符串中出现多组匹配的时候,可以都匹配出来。。。。

//求子串位置的定位函数index(***,***,int **)

#include <iostream>
#include <string>

using namespace std;

int index(const char *res, const char *str, int pos)
{
/* 若串 S 中从第pos(S 的下标0≤pos<StrLength(S))个字符

起存在和串 T 相同的子串,则称匹配成功,返回第一个

这样的子串在串 S 中的下标,否则返回 -1    */
 int i = pos, j = 0;
 while ( res[i+j] != '/0'&& str[j] != '/0')

  if ( res[i+j] == str[j] )
   j ++; // 继续比较后一字符
  else
  {
   i ++; j = 0; // 重新开始新的一轮匹配
  }


  if ( str[j] == '/0')
   return i+1; // 匹配成功   返回下标
  else
   return -1; // 串S中(第pos个字符起)不存在和串T相同的子串
}


int main()
{
   char res[100];
   char str[20];

   cout<<"input the context to be matched: "<<endl;  
   cin.getline(res,100,'/n');
 
   cout<<"input the key character:"<<endl;
   cin.getline(str,20,'/n');
 
   cout <<res<<endl;
   cout <<str<<endl;
 
   int position = -1;  //want to specify this variable, use cin....
   int index_=position;
   int count=0;
   do
   {
    index_ = index(res, str, index_);
    if( -1 == index_ )
     cout<<"so now,there is no more matching position"<<endl;
    else
    {
     count++;
     cout <<"the "<<count<<" matching characters: "<< index_<<endl; 
    }
   }while(index_ != -1);

   return 0;
}

 

 

//同时,如果要追求word里面的那样一种方式:

//查找出一个匹配之后就先suspend,在enter后继续匹配

//在while循环条件里面加上限制就可以了,在这里就不再罗嗦了。。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值