数据结构——模式匹配

#include <iostream>
using namespace std;

#define MaxStrSize 256
typedef unsigned
char MyString[MaxStrSize+1]; //0号单元存放串的长度
/*

掩饰符号类型。例如当需要定义多个包含80个元素的数组a,b,c时,可以这样定义:
typedef char Array_eighty[80];
Array_eighty a,b,c;

也可以这样隐藏指针:
typedef char * pstr;
int mystrcmp(pstr, pstr);
*/

//打印串
void StrPrint(MyString &S)
{
if(S[0]<=0)
{
cout
<<"空串!"<<endl;
}
else
{
int i=1;
while(S[i] != '\0')
{
cout
<<S[i];
i
++;
}
}
}
//模式匹配
int Index(MyString s,MyString t,int pos)
{
//返回子串t在主串s中第pos个字符之后的位置。如不存在返回0。
int i=pos,j=1;
while(i<=s[0] && j<=t[0])
{
if(s[i]==t[j])
{
i
++;
j
++;
}
else
{
i
=i-j+2;
j
=1;
}
}
if(j>t[0])
return i-t[0];
else
return 0;
}
//给串赋值
void Build_MyString(MyString s,char *str)
{
int length=strlen(str);
s[
0]=length;
int i=0;
while(str[i]!='\0')
{
s[i
+1]=str[i];
i
++;
}
s[i
+1]='\0';
}

int main()
{
MyString S1;
char *str1="ababcabcacbab";
Build_MyString(S1,str1);
cout
<<S1[0]-0<<endl; //将0号单元存放的串的长度变换为整型输出
StrPrint(S1);
cout
<<endl;

MyString S2;
char *str2="abcac";
Build_MyString(S2,str2);
cout
<<S2[0]-0<<endl;
StrPrint(S2);

cout
<<endl<<Index(S1,S2,1)<<endl;
return 0;
}

 

posted @ 2010-07-31 20:36  忧国忧铭  Views(392)  Comments(0)    收藏  举报