Package Org.loda.string;import org.junit.assert;/** * * @ClassName: Naivestringmatcher * @Description: Plain String Lookup * * TEXT:ABCABAABCABAC * Pattern:abaa * * @author Minjun * @date July 7, 2015 afternoon 4:02:14 * */public Clas s naivestringmatcher {public static void main (string[] args) throws Exception {//original text String text = "Abcabaabcabac";//Lookup Mode string pattern = "Abaa";//The position of the first occurrence of the pattern in the text int index = indexOf (text, pattern); SYSTEM.OUT.PRINTLN (index);} private static int IndexOf (string text, string pattern) {assert.assertnotnull (text); Assert.assertnotnull (pattern); int tLen = Text.length (); int plen = Pattern.length (); if (TLen < Plen) return-1;// Offset each time to the right to compare text and patternfor (int i = 0; i < Tlen-plen + 1; i++) {int j;//up to Plen wheel comparison for (j = 0; J < Plen; J + +) {/ /If found unequal immediately stop comparing if (Text.charat (i + j)! = Pattern.charat (j)) {Break;}} After the comparison is complete, if you compare plen times, the description performs a complete comparison and finds the location of the pattern iif (j = = Plen) {return i;}} If the position of the pattern is still not found, the description does not exist in the text patternreturn-1;}}
Introduction to Algorithm--naïve string matching algorithm