/* Determine all possible occurences of pattern string in text string using KMP technique*/ #include #include #define MAXPATLEN 80 #define EOS 0 void preprocpat1(pat,next) /* Produces slower failure links, but capable of continuing after match */ char *pat; int next[]; { int i,j; i=0; j=next[0]= -1; do { if (j==(-1)||pat[i]==pat[j]) { i++; j++; next[i]=j; } else j=next[j]; } while (pat[i]!=EOS); printf("Fail link table 1\n"); for (i=0;pat[i]!=EOS;i++) printf("%d %c %d\n",i,pat[i],next[i]); } void preprocpat2(pat,next) /* Produces faster failure links, but INcapable of continuing after match */ char *pat; int next[]; { int i,j; i=0; j=next[0]= -1; do { if (j==(-1)||pat[i]==pat[j]) { i++; j++; next[i]=(pat[j]==pat[i]) ? next[j] : j; } else j=next[j]; } while (pat[i]!=EOS); printf("Fail link table 2\n"); for (i=0;pat[i]!=EOS;i++) printf("%d %c %d\n",i,pat[i],next[i]); } void match(text1,pat) char *text1,*pat; { int next1[MAXPATLEN],next2[MAXPATLEN],i,j; char *text; char printSymbol=' '; if (*pat==EOS) return; preprocpat1(pat,next1); preprocpat2(pat,next2); printf("%s\n",text1); text=text1; for (j=0; *text!=EOS;) if (j==(-1) || pat[j]== *text) { if (pat[j+1]==EOS) printSymbol='^'; if (pat[j+1]==EOS && *(text+1)!=EOS) j=next1[j]; /*restart*/ else { printf("%c",printSymbol); printSymbol=' '; text++; j++; } } else j=next2[j]; printf("\n"); } main() { char pat[80],text[80]; printf("Enter text & pattern\n"); /*variable text is string 1, variable pat is string 2*/ while (scanf("%s %s",text,pat)!=EOF) { match(text,pat); printf("Enter text & pattern\n"); } }