C++ 模式匹配

算法思想:(普通方法)

 一、char[]存储:
 1.定义主串S,目标串T;
 2.i,j分别指向S和T的第一个字符,开始比较:
     Ⅰ.若相等:i++;j++;  (i,j都向后移)
     Ⅱ.若不等,i=i-j+1;j=0;(i向后S移一位,j重新指向T第一个字符),继续比较。
 
 二、string存储:     
 1.定义主串S,目标串T;
 2.初始i=0;将T与S的子串(i开始,长度为T.lenth()),进行比较:
     Ⅰ.若相等:则匹配成功;
     Ⅱ.若不等,i++(子串后移),继续比较。
     
 三、s.find(t);

算法实现:

//char[]存储
int Index(char *s,char *t)
{
	int i=0,j=0;
	while(i<strlen(s)&&j<strlen(t))
	{
		if(s[i]==t[j])
		{
			i++;
			j++;
		}
		else
		{
			i=i-j+1;
			j=0;
		}
	}
	if(j=strlen(t))
		{
			cout<<"成功";
             return 0;
		}
		else
		{	cout<<"失败";
			return 0;
	     }
	return 0;
}
//string 存储
int comp(string s1,string s2)
{
	int i=0;
	while(s2.compare(s1.substr(i,s2.length()))!=0)
	          i++;
	if(i<=s1.length()-s2.length())
	{
		cout<<"从第"<<i+1<<"个字符开始匹配:"<<endl<<s1<<endl;
		for (int k = 0; k < i; k++)
		{
			cout<<" ";
		}
		cout<<s2<<endl<<endl;
	}
	else
	{
		cout<<"不匹配"<<endl<<s1<<endl;s2<<endl<<endl;
		return 0;
	}
	
}
//s.find(t);
void s_find(string T,string S)
{
		if(T.find(S)!=-1)
		cout<<"匹配"<<endl;
		else
		cout<<"不匹配"<<endl;
}

运行代码


#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;

int Index(char *s, char *t);
int comp(string s1,string s2);
void s_find(string T,string S);
int main()
{
	string S="0123456789";
	string s1="1234";  comp(S,s1);//s_find(S,s1)
	string s2="567";   comp(S,s2);//s_find(S,s2)
	string s3="89";    comp(S,s3);//s_find(S,s3)

	char C[]="0123456789";
	char c1[]="0";    //Index(C,c1);
	char c2[]="12";   //Index(C,c2);
	char c3[]="345";  //Index(C,c3);
	char c4[]="7890"; //Index(C,c4);
	
	system("pause");
	return 0;
}
int Index(char *s,char *t)
{
	int i=0,j=0;
	while(i<strlen(s)&&j<strlen(t))
	{
		if(s[i]==t[j])
		{
			i++;
			j++;
			//cout<<endl<<"成功 "<<i<<" "<<j<<endl;
		}
		else
		{
			i=i-j+1;
			j=0;
			//cout<<endl<<"失败 "<<i<<" "<<j<<endl;
		}
	}
	if(j=strlen(t))
		{
			cout<<"成功";
             return 0;
		}
		else
		{	cout<<"失败";
			return 0;
	     }
	return 0;
}
int comp(string s1,string s2)
{
	int i=0;
	while(i<s1.length()&&s2.compare(s1.substr(i,s2.length()))!=0)
	          i++;
	if(i<=s1.length()-s2.length())
	{
		cout<<"从第"<<i+1<<"个字符开始匹配:"<<endl<<s1<<endl;
		for (int k = 0; k < i; k++)
		{
			cout<<" ";
		}
		cout<<s2<<endl<<endl;
	}
	else
	{
		cout<<"不匹配"<<endl<<s1<<endl;
		cout<<s2<<endl<<endl;
		return 0;
	}
}
void s_find(string T,string S)
{
		if(T.find(S)!=-1)
			cout<<"匹配"<<endl;
		else
			cout<<"不匹配"<<endl;
}

运行结果

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值