算法思想:(普通方法)
一、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);
算法实现:
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;
}
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;
}
}
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);
string s2="567"; comp(S,s2);
string s3="89"; comp(S,s3);
char C[]="0123456789";
char c1[]="0";
char c2[]="12";
char c3[]="345";
char c4[]="7890";
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++;
}
else
{
i=i-j+1;
j=0;
}
}
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;
}
运行结果
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200306093619659.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80MzY1NjMyNw==,size_16,color_FFFFFF,t_70)