#include
#include
#include
const int maxlen=128;
class string{
public:
string(); //构造字符串
int match(); //进行字符串匹配
int getmainlenght(); //计算主字符串长度
int getsublenght(); //计算子字符串长度
out();
private:
char *ch,*zh;
int t[20];
};
string::string()
{
ch=new char[maxlen+1];
zh=new char[maxlen+1];
if(!ch || !zh)
{
cout<<"Allocation Error\n";}
else
{
cout<<"输入主字符串:\n";
cin>>zh;
cout<<"输入子字符串:\n";
cin>>ch;
}
for(int i=0;i<20;i++)
t[i]=-2;
}
int string::getmainlenght()
{
return strlen(zh);
}
int string::getsublenght()
{
return strlen(ch);
}
int string::match()
{
int i=0,j=0;
char *p,*s;
p=zh,s=ch;
if(*ch&&*zh)
while(i<=getmainlenght()-getsublenght())
{
if(*p++==*s++)
{
if(!*s)
{
t[j]=i;
j++;
}
}
else
{
i++,p=zh+i,s=ch;
}
}
return 0;
return -1;
}
string::out()
{
for(int j=0;t[j]!=-2;j++)
cout<<"匹配从第"<
}
void main()
{
int i,len1,len2;
string mh;
len1=mh.getmainlenght();
len2=mh.getsublenght();
cout<<"主字符串个数是:"<
cout<<"子字符串个数是:"<
i=mh.match();
if(i==-1)
cout<<"find nothing!"< else
mh.out();
}
这个程序的功能是从主串中找到子串的位置,主串中可能有多个子串,把他们的位置记录在t[20]中,先赋值-2是为了作为结束的标志。
应该说这个c++的类不怎么规范阿(大虾们可以帮我改一下错),c++忘的差不多了,五一要补补。
int string::match()
{
int i=0,j=0;
char *p,*s;
p=zh,s=ch;
if(*ch&&*zh)
while(i<=getmainlenght()-getsublenght())
{
if(*p++==*s++)
{
if(!*s)
{
t[j]=i;
j++;
}
}
else
{
i++,p=zh+i,s=ch;
}
}
return 0;
return -1;
}
match函数是这个程序的关键,我这里解释一下了。
if语句确保两者都不惟空。
while的结束条件是i<=主,子字符串的差。如:主字符串有20个字符而字字符串有4个,那么当主字符串的指针指向16(从0开始),他后面只有四个字符,只能做最后一次的匹配。
i++,p=zh+i,s=ch;这句是跳过部分匹配的字符。如:主:achmxzsdjfhsdf,子:hmxzj
主串中的hmzj符合但最后一个不行,那就直接跳过了。
附上一个运行结果:
输入主字符串:
4dsgj;34e;jg;e34
输入子字符串:
4
主字符串个数是:17
子字符串个数是:2
匹配从第0个开始
匹配从第7个开始
匹配从第15个开始
ress any key to continue
写的有些别扭阿,以后努力。
----by adrian
阅读(2773) | 评论(2) | 转发(0) |