/** * @file Match.java * @synopsis A simple program to find the first match between * a pattern P and a text T. * CONVENTION: * The first index (i=0) of arrays are not used. * * @author Chee Yap * @date Apr 25, 2001 (for Basic Algorithms class) */ public class Match { // Members: char[] P; // This is pattern char[] T; // This is the text // Constructors: Match(char[] p, char[] t) { P = p; T = t; } // // Methods: /****************************************************** THIS IS THE MAIN ROUTINE ******************************************************/ public int find(int start) { // init: int j = start; // text index int k = 1; // pattern index // loop: while (j < T.length) { if (k >= P.length) return(j - k + 1); if (T[j] == P[k]) { j++; k++; } else { j = j - k + 2; k = 1; } } // while // not found: return(-1); } // find() /****************************************************** prints data ******************************************************/ void output() { System.out.print("> Pattern = \""); for (int i=1; i< P.length; i++) System.out.print(P[i]); System.out.print("\"\n> Text = \""); for (int i=1; i< T.length; i++) System.out.print(T[i]); System.out.println("\""); } // output() /****************************************************** Main method ******************************************************/ public static void main( String[] args) { // sample input with 6 keys // (the first is a dummy key) // char[] p = {'0', 'o', 'u'}; char[] p = {'0', 'y', 'o', 'u'}; char[] t = {'0', 'a', 'r', 'e', ' ', 'y', 'o', 'u', ' ', 'a', ' ', 'y', 'o', 'u', 't', 'h', '?'}; // construct a Match object Match m = new Match(p, t); m.output(); // print data // find all matches int f = m.find(1); if (f<1) System.out.println(">> No match found"); else { while (f>=1) { System.out.println(">> Match found at position " + f); f = m.find(f+1); }//while }//else } // main }//class Match