[英]How do I find and replace a word one occurrence at a time in java?
我正在開發一個文本編輯器,我希望用戶能夠找到並替換他們選擇的單詞。 我目前有替換單詞的代碼,但它一次替換了所有出現的單詞。 我實際上想替換當時出現的單詞。 例如,如果用戶想用“狗”替換“貓”,他們必須單擊一個按鈕,它將替換它找到的第一個“貓”,然后用戶將不得不再次單擊該按鈕以替換另一個一次發生一次。 我確實瀏覽了這里的一些問題,但其中大多數似乎一次替換了所有出現的問題,這就是我遇到的問題。 這是我到目前為止。 在此先感謝任何能夠幫助我的人。
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();}
}
});
}
}
用if
替換while
。
你的循環說“只要你發現更多的出現,就繼續替換”。 如果您希望它僅替換第一次出現,它可能應該是“如果您找到一個出現,則替換”。
另一種解決方案可能是將“替換”按鈕重命名為“全部替換”;-)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.