简体   繁体   中英

How do I find and replace a word one occurrence at a time in java?

I am working on a text editor and I want the user to be able to find and replace a word of their choosing. I currently have the code to replace the word, but it replaces all the occurrences of the word at once. I actually want to replace the word once occurrence at the time. For example, if the user wants to replace "cat" with "dog" they will have to click a button and it will replace the first "cat" that it finds and then the user will have to click the button again to replace the other occurrences one at a time. I did look through some of the questions on here, but most of them seem to replace all the occurrences at once and that is the issue I have. This is what I have so far. Thanks in advance to anyone that is able to help me.

class Bottom extends JPanel
{
  private JPanel bottomPanel = new JPanel();
  private JButton replaceButton = new JButton("Replace");
  private JTextField textField = new JTextField("", 15);;
  private JLabel label = new JLabel(" with ");
  private JTextField textField2 = new JTextField("", 15);

  public Bottom()
  {
    bottomPanel.add(replaceButton);
    bottomPanel.add(textField);
    bottomPanel.add(label);
    bottomPanel.add(textField2);
    add(bottomPanel);

    replaceButton.addActionListener( new ActionListener()
    {
        public void actionPerformed(ActionEvent e)
        {
            try{
            String findText = textField.getText();
            int findTextLength = findText.length();
            String replaceText = textField2.getText();
            int replaceTextLength = replaceText.length();
            Document doc = textArea.getDocument();
            String text = doc.getText(0, doc.getLength());
            int counter = 0;
            int lengthOffset = 0;

            while ((lengthOffset = text.indexOf(findText, lengthOffset)) != -1)
            {
                int replaceOffset = lengthOffset + ((replaceTextLength - findTextLength) * counter);
                textArea.select(replaceOffset, replaceOffset + findTextLength);
                textArea.replaceSelection(replaceText);

                lengthOffset += replaceTextLength;

                counter++;
            }
            }catch(BadLocationException b){b.printStackTrace();}
        }
    });
}

}

Replace that while with an if .

Your loop says "as long as you find more occurrences, keep replacing". If you want it to replace just the first occurrence, it should probably be "if you find an occurrence, replace".

Another solution might be to rename your "Replace" button to "Replace all" ;-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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