/****************************************
* Feng Yu
* Peking University
*********************************/
#include <stdio.h>
/* multi-byte check need correct*/
#define ISMULTILO(x) (((0xff & (x))>=0x40 && (0xff &(x))<=0x7e) || \
((0xff & (x))>=0xa1 && (0xff
&(x))<=0xfe))
#define ISMULTIHI(x) ((0xff & (x))>=0xa1 && (0xff &(x))<=0xf9)
/* get a char from pos and store to x, then inc pos */
#define sgetch(x, s, pos,d) {printf("0x%x,%d,%d\n",*(s+pos),pos,ISMULTIHI(*(s+
pos))); \
if(ISMULTIHI(*(s+pos)) &&
ISMULTILO(*(s+pos+1))) \
{ x=*((short int*)(s+pos));d=sizeof(short
int);} \
else {x=(short int)(*(s+pos));d=sizeof(char);}
}
int kmp_search(char* foo, char* string)/* search string for foo*/
{
int fl;
int l;
short int x;
short int* newfoo;
short int* next;
int i;
int j;
int d;
fl=strlen(foo);
newfoo=(int*)malloc(sizeof(short int)*(fl+1)); /* convert
the multibyte string to 2-bytes string*/
next=(int*)malloc(sizeof(short int)*(fl+1));
i=0;
j=0;
while(i<fl){
sgetch(newfoo[j],foo,i,d)
i+=d;
j++;
}
newfoo[j]=0;
fl=j; /* store the real foo size */
next[0]=-1; /* get the next array*/
j=-1;
i=0;
while(i<fl-1){
if(-1!=j) while(newfoo[i]!=newfoo[j]){j=next[j];
if(j==-1)break;}
i++;j++;
if(newfoo[i]==newfoo[j]) next[i]=next[j];
else next[i]=j;
}
/*search ...*/
i=0;j=0;l=strlen(string);
while(i<fl && j<l){
sgetch(x,string,j,d);
printf("%X,%d\t",x,d);
if(i==-1) i++,j+=d; else if(newfoo[i]==x) i++,j+=d;
else
i=next[i];
}
free(newfoo);
free(next);
if(i==fl) return j-strlen(foo);
else return -1;
}
int main(int argc, char* argv[]){
int x=kmp_search(argv[2],argv[1]);
//int x=kmp_search("宋","三国人");
printf("%d",x);
return x;
}
--
FROM 162.105.173.82