Wie man die Positionen der alle übereinstimmungen in einem String?

Ich habe ein text-Dokument, und eine Abfrage (die Abfrage könnte mehr als ein Wort). Ich möchte zu finden, die position aller vorkommen der Abfrage in das Dokument.

Dachte ich an die documentText.indexOf(query) oder regular expressions, aber ich konnte nicht damit es funktioniert.

Ich am Ende mit der folgenden Methode:

Zuerst habe ich erstellen Sie einen Datentyp namens QueryOccurrence

public class QueryOccurrence implements Serializable{
  public QueryOccurrence(){}
  private int start;
  private int end;      

  public QueryOccurrence(int nameStart,int nameEnd,String nameText){
    start=nameStart;
    end=nameEnd;        
  }

  public int getStart(){
    return start;
  }

  public int getEnd(){
    return end;
  }

  public void SetStart(int i){
    start=i;
  }

  public void SetEnd(int i){
     end=i;
  }
}

Dann, ich habe diesen Datentyp in der folgenden Methode:

    public static List<QueryOccurrence>FindQueryPositions(String documentText, String query){

    //Normalize do the following: lower case, trim, and remove punctuation
    String normalizedQuery = Normalize.Normalize(query);
    String normalizedDocument = Normalize.Normalize(documentText);

    String[] documentWords = normalizedDocument.split(" ");;               
    String[] queryArray = normalizedQuery.split(" ");


    List<QueryOccurrence> foundQueries = new ArrayList();
    QueryOccurrence foundQuery = new QueryOccurrence();

    int index = 0;

    for (String word : documentWords) {            

        if (word.equals(queryArray[0])){
            foundQuery.SetStart(index);
        }

        if (word.equals(queryArray[queryArray.length-1])){
            foundQuery.SetEnd(index);
            if((foundQuery.End()-foundQuery.Start())+1==queryArray.length){

                //add the found query to the list
                foundQueries.add(foundQuery);
                //flush the foundQuery variable to use it again
                foundQuery= new QueryOccurrence();
            }
        }

        index++;
    }
    return foundQueries;
}

Diese Methode gibt eine Liste aller vorkommen der Abfrage im Dokument die jeweils Ihre position.

Könnte Sie schlagen alle einfacher und schneller Weg, um diese Aufgabe zu erfüllen.

Dank

InformationsquelleAutor user692704 | 2012-11-10
Schreibe einen Kommentar