2014-04-04 75 views
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); 
} 
+0

一個簡短而親切的解決方案'String'是不可改變的,調用'toLowerCase()'方法返回一個新字符串。至少,將調用'toLowerCase()'的結果重新分配給您正在調用它的變量(在方法開始附近的'textToFind'和'CurrentText')。 –

+0

我自己解決了這個問題,在幾個小時內發佈了代碼 – Andy

+0

@因此,您在OP中發佈的代碼相當多。 – rpg711

回答

0

你有很多冗餘代碼。下面是使用String.indexOf

public static void searchTextToFind(String textToFind) { 

    highlighter.removeAllHighlights(); 
    textToFind = textToFind.toLowerCase(); //STRINGS ARE IMMUTABLE OBJECTS 
    String currentText = textPane.getText(); //UPPERCASE LOCALS ARE EVIL 
    currentText = currentText.toLowerCase(); //STRINGS ARE IMMUTABLE OBJECTS 
    int offset = 0; 
    for(int index = currentText.indexOf(textToFind, offset); index >= 0; index = currentText.indexOf(textToFind, offset)){ 
     int startIndex = currentText.indexOf(textToFind, offset); 
     int endIndex = startIndex + textToFind.length() - 1; //this gets you the inclusive endIndex. 
     textPane.setSelectionStart(startIndex); 
     textPane.setSelectionEnd(endIndex); 
     offset = startIndex + 1; //begin the NEXT search at startIndex + 1 so we don't match the same string over and over again 

     System.out.println(startIndex); 
     System.out.println(endIndex); 
     try { 
      highlighter 
      .addHighlight(startIndex, endIndex, myHighlightPainter); 

     } catch (BadLocationException e) { 
      e.printStackTrace(); 
     }  
    } 
} 
相關問題