The Java Program: Search.java

  1 import java.text.*;
  2 
  3 public class Search {
  4   public static int indexOf(String source, String pattern) {
  5     // Obtain a collator
  6     RuleBasedCollator rbc=(RuleBasedCollator)Collator.getInstance();
  7     rbc.setStrength(Collator.SECONDARY);
  8 
  9     CollationElementIterator textCEI;
 10     CollationElementIterator patCEI;
 11     textCEI = rbc.getCollationElementIterator(source);
 12     patCEI = rbc.getCollationElementIterator(pattern);
 13 
 14     // e1 will contain the collation element for the source
 15     // e2 will contain the collation element for the pattern
 16     int e1, e2;
 17     int startMatch = -1;
 18 
 19     // initialize e2 with the first collation element in the pattern
 20     e2 = patCEI.next();
 21 
 22     while ((e1 = textCEI.next())!=CollationElementIterator.NULLORDER) {
 23       if (e1 == e2) { // if the elements match
 24         if (startMatch == -1) startMatch = textCEI.getOffset();
 25         e2 = patCEI.next(); // increment to the next element
 26         if (e2 == CollationElementIterator.NULLORDER)
 27           break;
 28       } else { // elements do not match
 29         if (startMatch != -1) {
 30           patCEI.reset();
 31           e2 = patCEI.next();
 32           startMatch = -1;
 33         }
 34       }
 35     }
 36     return startMatch;
 37   }
 38 
 39   public static void main(String [] args) {
 40     String text = "Wie hei\u00DFen Sie?"; // Wie heißen Sie?
 41     String pattern = "heissen";
 42 
 43     int index = indexOf(text, pattern);
 44     if (index != -1)
 45       System.out.println("Found a match at: " + index);
 46     else
 47       System.out.println("No match found!");
 48   }
 49 }