CPP

C++串的简单模式匹配

先依次输入主串S及模式串T的值,然后调用子串的定位函数Index( )进行模式匹配。匹配成功后返回T在S中第pos个字符之后的位置,否则返回0。
#include <stdio.h>
#define MAXSTRLEN 255
typedef unsigned char sstring[MAXSTRLEN+1];
int Index(sstring &S,sstring T,int pos)
{  //返回子串T在主串中第pos个字符之后的位置
   //若不返回,返回0。其中T非空,1<=pos<=strlength(s)
    int i,j;
i=pos;
j=1;
while(i<=S[0]&&j<=T[0])
{
    if(S==T[j])
    {
       ++i;
       ++j;
    }
    else
    {
       i=i-j+2;
       j=1;
    }
}
if(j>T[0]) return i-T[0];
else    return 0;
}
void main()
{
int re,i,pos;
sstring S1,S2;
printf("\nEnter length of the string S1 and the string S1:\n");
scanf("%d",&S1[0]);
for(i=1;i<=S1[0];i++)
{
  scanf("%c",&S1);
}
printf("\nEnter length of the string S2 and the string S2:\n");
scanf("%d",&S2[0]);
for(i=1;i<=S2[0];i++)
{
scanf("%c",&S2);
}
printf("\nInput positionof beginning:");
scanf("%d",&pos);
re=Index(S1,S2,pos);
if(re!=0)
   printf("\nThe posision is %d\n",&re);
else
   printf("\nNot found!");
}