Jay Jay - 1 year ago 79
Java Question

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()

replaceButton.addActionListener( new ActionListener()
public void actionPerformed(ActionEvent e)
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);

lengthOffset += replaceTextLength;

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


This problem has already been answered, but I wanted to expand on the same subject so I am adding another concern onto this question. I am trying to do the same thing this block of code already does, but in a much simpler and easier way. The only issue I am having is that when this code runs, it replaces the whole text area's text and I just want it to replace a specific word one occurrence at a time. This is what the simplified code looks like:

String findText = textField.getText();
String replaceText = textField2.getText();
String text = textArea.getText();

text += text.replaceFirst(findText, replaceText);

Answer Source

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" ;-)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download