01: package com.sun.portal.wsrp.common;
02:
03: public class Boyer {
04:
05: public static int indexOf(String text, String pattern) {
06: return indexOf(text, pattern, 0);
07: }
08:
09: public static int indexOf(String text, String pattern,
10: int startIndex) {
11:
12: if (text == null || pattern == null) {
13: return -1;
14: }
15:
16: int textLength = text.length();
17: int patternLength = pattern.length();
18: char[] patternCharArray = pattern.toCharArray();
19: int[] skip = new int[256];
20:
21: //
22: // Calculate the skip
23: //
24:
25: for (int i = 0; i < 256; i++) {
26: skip[i] = patternLength;
27: }
28:
29: for (int i = 0; i < patternLength - 1; i++) {
30: skip[patternCharArray[i] & 0xff] = patternLength - i - 1;
31: }
32:
33: //
34: // Find the index
35: //
36: char currentChar = 0;
37: final int lastPatternChar = patternCharArray[patternLength - 1];
38:
39: for (int testForward = startIndex + patternLength - 1; testForward < textLength; testForward += skip[currentChar & 0xff]) {
40: //
41: // For both pattern and test,
42: // compare working right to left
43: //
44: currentChar = text.charAt(testForward);
45: if (currentChar != lastPatternChar) {
46: continue;
47: }
48:
49: // step back through pattern and text to
50: // make sure the match is there.
51:
52: boolean mismatch = false;
53:
54: for (int textBackward = testForward - 1, patternBackward = patternLength - 2; patternBackward >= 0; textBackward--, patternBackward--) {
55:
56: if (text.charAt(textBackward) != patternCharArray[patternBackward]) {
57: mismatch = true;
58: break;
59: }
60: }
61: if (mismatch) {
62: continue;
63: }
64:
65: //
66: // We found a match.
67: //
68: return testForward - patternLength + 1;
69:
70: }
71: return -1;
72:
73: }
74:
75: }
|