텍스트 문서와 쿼리가 있습니다 (쿼리는 둘 이상의 단어 일 수 있음). 문서에서 쿼리의 모든 발생 위치를 찾고 싶습니다.문자열에서 모든 일치 항목의 위치를 얻는 방법은 무엇입니까?
나는 documentText.indexOf(query)
을 생각하거나 정규 표현식을 사용했지만 작동하지 못했습니다.
나는 다음과 같은 방법으로 끝낼 :
는 첫째, 나는 그런 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;
}
}
라는 데이터 유형을 만들 수있다, 나는 다음과 같은 방법이 데이터 유형을 사용하고 있습니다 :
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;
}
이 메서드는 문서에서 쿼리의 모든 항목 목록을 위치와 함께 반환합니다.
이 작업을 수행하는 더 쉽고 빠른 방법을 제안 해주세요.
감사
이렇게하면 도움이됩니다. ['String # indexOf (String, int)'] (http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#indexOf%28java. lang.String, % 20int % 29) –