此段代码是我在数据结构课上敲的代码,仅供大家参考
#include<iostream>
#include<string>using namespace std;
void main()
{
string s1,s2;
cout<<"请输入模板串s1:";
cin>>s1;
cout<<"请输入目标串s2:";
cin>>s2;
int n1,n2;
n1=s1.length();
n2=s2.length();
cout<<"模板串为:"<<s1<<"串长为:"<<n1<<endl;
cout<<"目标串为:"<<s2<<"串长为:"<<n2<<endl;
int i,j,succ=0;
int n=0;
int m=0;
for(i=0;i<n1-n2+1;i++)
{
succ=1;n++;
for(j=0;j<n2;j++)
{
if(s1[j+i]!=s2[j])
{
succ=0;
break;
}
}
if(succ==1) m++;
}
if(succ)
{
cout<<"发现!位置是:"<<i<<endl;
cout<<"总配对次数为:"<<n<<endl;
cout<<"总相同个数:" << m<<endl;
}
else
{
cout<<"未发现!"<<endl;
cout<<"总配对次数为:"<<n<<endl;
}
}