子串查找问题改进算法



//实现了字符串匹配并输出子串 




#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;
}











评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值