0
我有一個很大的字符串(XML樣式),我提供了一個文本字段來捕獲要搜索的單詞。所有找到的單詞應該突出顯示。查找字符串中的多個單詞並獲取索引
我遇到的問題是,該字可以在該字符串中出現多次,但只有第一個或最後一個字被突出顯示。 我發現問題是selectionStart和ending總是相同的。
你能幫助我嗎?
public static void searchTextToFind(String textToFind) {
highlighter.removeAllHighlights();
String CurrentText = textPane.getText();
StringReader readtext;
BufferedReader readBuffer;
int i = 0;
int matches = 0;
readtext = new StringReader(CurrentText);
readBuffer = new BufferedReader(readtext);
String line;
try {
i = CurrentText.indexOf(textToFind);
int start = 0;
int end = 0;
Pattern p = Pattern.compile(textToFind);
while ((line = readBuffer.readLine()) != null) {
Matcher m = p.matcher(line);
// indicate all matches on the line
while (m.find()) {
matches++;
while (i >= 0) {
textPane.setSelectionStart(i);
textPane.setSelectionEnd(i + textToFind.length());
i = CurrentText.indexOf(textToFind, i + 1);
start = textPane.getSelectionStart();
end = textPane.getSelectionEnd();
try {
highlighter.addHighlight(start, end,
myHighlightPainter);
} catch (BadLocationException e) {
e.printStackTrace();
}
}
}
}
} catch (IOException e1) {
e1.printStackTrace();
}
JOptionPane.showMessageDialog(paneXML,
matches+" matches have been found", "Matched",
JOptionPane.INFORMATION_MESSAGE);
}
一個簡短而親切的解決方案'String'是不可改變的,調用'toLowerCase()'方法返回一個新字符串。至少,將調用'toLowerCase()'的結果重新分配給您正在調用它的變量(在方法開始附近的'textToFind'和'CurrentText')。 –
我自己解決了這個問題,在幾個小時內發佈了代碼 – Andy
@因此,您在OP中發佈的代碼相當多。 – rpg711