简体   繁体   English

突出显示所有出现的字符串

[英]Highlight all occurrences of a string

I'm making a little Notepad program because I am very bored and thought I would try to implement a "Find" feature within my program. 我正在做一个小记事本程序,因为我很无聊,并认为我会尝试在程序中实现“查找”功能。

I want to highlight every word that matches a given string. 我想突出显示与给定字符串匹配的每个单词。

here is the main chunk of code 这是主要的代码块

if(e.getSource() == m_find){
    String s = (String)JOptionPane.showInputDialog("Find Word", "Please search a word");
       if(m_area.getText().contains(s)){
         int start = m_area.getText().indexOf(s);
         int length = start + s.length();
           try {
               highlight.addHighlight(start, length, painter);
           } catch (BadLocationException e1) {
               e1.printStackTrace();
           }
    }

This only gets the first occurrence of the word, how would I be able to high every occurrence of the word. 这只会得到单词的第一次出现,我如何才能提高单词的每次出现。

I'm sure there are many ways, but one would be to use a while loop to keep highlighting occurrences if there are more to find. 我敢肯定有很多方法,但是如果有更多可以找到的方法,一种方法是使用while循环来突出显示事件。 Then you would only keep looking at the String past what you already highlighted. 然后,您将仅在已经突出显示的内容之后继续查看String。

String stringToFindWordsIn = m_area.getText();

while(stringToFindWordsIn.contains(s)){
    // highlight the word

    // Make stringToFindWordsIn the substring from where you just highlighted to the end (drop off everything before and including the word you just highlighted)
}

You can use indexOf with start parameter to start searching form given index, example implementation: 您可以将indexOf与start参数一起使用,以开始搜索给定索引的表单,示例实现:

int start = 0;
do {
    start = m_area.getText().indexOf(s, start);
    int length = start + s.length();
    try {
        highlight.addHighlight(start, length, painter);
    } catch (BadLocationException e1) {
        e1.printStackTrace();
    }
    start += length;
}

Try this: 尝试这个:

if(e.getSource() == m_find){
        String s = (String)JOptionPane.showInputDialog("Find Word", "Please search a word");
       if(m_area.getText().contains(s)){
         String text = m_area.getText();
         int start = text.indexOf(s);
         while (start >= 0) {
           int length = start + s.length();
           try {
               highlight.addHighlight(start, length, painter);
           } catch (BadLocationException e1) {
               e1.printStackTrace();
           }
           start = text.indexOf(s, start + 1);
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM