//实现了字符串匹配并输出子串
#include<iostream>
using namespace std;
#include<string.h>
class String
{
char *str;
int length;
public :
String(char *);
void show(int i)
{
for(int j = i;j<length;j++)
cout<<str[j];
cout<<endl;
}
friend int String_match_pos(String &s1,String & s2);
};
String::String(char * p)
{
length = strlen(p);
str = new char[length];
strcpy(str,p);
}
int String_match_pos(String &p,String & s)
{
int i = 0,j = 0;
while(i <p.length && j <s.length)
{
if(p.str[i] == s.str[j])
{
i++;
j++;
}
else
{
i = i - j+1; //比了几个再倒回去,从下一个开始
j = 0;
}
}
if(j == 0) //没有匹配的情况
return -1;
else
{
int k = i - s.length; //找到在父串中的匹配位置
return k;
}
}
int main()
{
char *p1 ;
p1 = new char [40];
strcpy(p1,"this is a string");
cout<<"父串为:"<<p1<<endl;
char *s1 ;
s1 = new char [40];
strcpy(s1,"my string is abc");
cout<<"短串为:"<<s1<<endl;
String p(p1),s(s1);
int pos = String_match_pos(p, s);
cout<<"pos: "<<pos<<endl;
if(pos != -1)
{
cout<<"子串为:";
p.show(pos);
}
else
{
cout<<"不能匹配"<<endl;
}
return 0;
}