在String中查找多个单词并获取索引

时间:2014-04-04 13:12:51

标签: java string indexing words

我有一个大字符串(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);
}

1 个答案:

答案 0 :(得分: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();
        }     
    }  
}