#include<stdio.h>
#include<stdlib.h>
typedef struct{
char *ch;
int len;
}HString;
void HstrAssign(HString *s,char *str)//串赋值
{
s->ch=NULL;
int i=0,j;
while(str[i]!='\0') i++;
if(!i) s->len=0;
else {
s->ch=(char*)calloc(i,sizeof(char));
s->len=i;
for(j=0;j<=i-1;j++) s->ch[j]=str[j];
}
}
void printhstr(HString s)//打印串中节点元素
{
int i;
printf("%d ",s.len);
for(i=0;i<s.len;i++)
printf("%c",s.ch[i]);
}
void HstrCompare(HString s1,HString s2)//串比较,strcmp
{
int i=0,t;
while(i<s1.len&&i<s2.len)
{
if(s1.ch[i]==s2.ch[i])i++;
else {t=s1.ch[i]-s2.ch[i];break;}
}
t=s1.ch[i]-s2.ch[i];
printf("%d\n",t);
}
void ClearHstr(HString *s)//清空一个串
{
if(s->ch) {free(s->ch);s->ch=NULL;}
s->len=0;
}
void HstrConcat(HString *s,HString s1,HString s2)//串的连接
{
//if(s->ch) free(s->ch);
s->len=s1.len+s2.len;
s->ch=(char*)calloc(s->len,sizeof(char));
int i=0;
while(i<s1.len) {s->ch[i]=s1.ch[i];i++;}
while(i<s->len){s->ch[i]=s2.ch[i-s1.len];i++;}
printhstr(*s);
}
void SubHstring(HString *sub,HString s,int pos,int length)//s中pos位置开始找长度为length子串
{
int i;
sub->len=length;
sub->ch=(char*)calloc(length,sizeof(char));
for(i=pos-1;i<pos+length-1;i++) sub->ch[i-pos+1]=s.ch[i];
printhstr(*sub);
}
void get_next(HString s,int next[])
{
int i,j;
i=0;j=-1;
next[0]=-1;
while(i<s.len)
{
if(-1==j||s.ch[i]==s.ch[j])
{
i++;j++;
if(s.ch[i]==s.ch[j]) next[i]=next[j];
else next[i]=j;
}
else j=next[j];
}
}
void kmp_search(void)//kmp算法
{
void get_next(HString s,int next[]);
char str1[100],str2[100];
printf("input str1:");
gets(str1);
printf("input str2:");
gets(str2);
HString s1,s2;
HstrAssign(&s1,str1);
HstrAssign(&s2,str2);
int next[s2.len];
get_next(s2,next);
int i,j;
i=0;j=0;
while(i<s1.len&&j<s2.len)
{
if(j==-1||s1.ch[i]==s2.ch[j]) {i++;j++;}
else j=next[j];
}
if(j==s2.len) printf("match at %dth",i-j+1);
else printf("not match");
}