【问题标题】:How do I find and replace a word one occurrence at a time in java?如何在java中一次查找和替换一个单词?
【发布时间】:2016-10-11 02:22:01
【问题描述】:

我正在开发一个文本编辑器,我希望用户能够找到并替换他们选择的单词。我目前有替换单词的代码,但它一次替换了所有出现的单词。我实际上想在当时出现一次替换这个词。例如,如果用户想用“狗”替换“猫”,他们将不得不单击一个按钮,它将替换它找到的第一个“猫”,然后用户必须再次单击该按钮来替换另一个一次发生一个。我确实查看了这里的一些问题,但其中大多数似乎一次替换了所有出现的问题,这就是我遇到的问题。这就是我到目前为止所拥有的。提前感谢任何能够帮助我的人。

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

}

【问题讨论】:

    标签: java replace


    【解决方案1】:

    while 替换为 if

    您的循环说“只要找到更多出现,就继续替换”。如果您希望它仅替换第一个匹配项,则可能应该是“如果找到匹配项,请替换”。

    另一种解决方案可能是将“替换”按钮重命名为“全部替换”;-)

    【讨论】:

    • 当然就是这么简单。我什至没有想到这一点。非常感谢。这绝对解决了整个问题,而无需使用 replaceFirst 方法。谢谢!
    猜你喜欢
    • 2016-08-19
    • 1970-01-01
    • 2014-06-12
    • 2010-12-19
    • 1970-01-01
    • 2013-11-09
    • 2012-10-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多