我手头的任务是向Jbutton添加一个事件,该事件将计算在JTextArea中显示的单词出现的次数。代码如下所示,但这计算了每个单词;

private void btnCountActionPerformed(java.awt.event.ActionEvent evt) {
    if(!(txtaInput.getText().trim().length()==0)){
        String a = String.valueOf(txtaInput.getText().split("\\s").length);
        lbl2.setText("the word java has appeared " + a + " times in the text area");
        lbl2.setForeground(Color.blue);
    }
    else{
       lbl2.setForeground(Color.red);
           lbl2.setText("no word to count ");
    }
}


帮助我弄清楚如何在JTextArea中输入特定单词(例如“ Jeff”)时进行单词计数。

最佳答案

这样尝试

    String[] words=txtaInput.getText().toLowerCase().trim().split(" "); //Consider words separated by space
    String StringToFind="yourString".toLowerCase();
    int count=0;
    for(String word : words)
    {
        if(word.contains(StringToFind)){
            count++;
        }
    }
    lbl2.setText("Count: "+ count);
    lbl2.setForeground(Color.blue);


我已经尝试过此代码

public class TestClass {
public static void main(String[] args) {
    String[] words="This is a paragraph and it's contain two same words so the count should be two".toLowerCase().split(" ");
    String StringToFind="two".toLowerCase();
    int count=0;
    for(String word : words)
    {
        if(word.contains(StringToFind)){
            count++;
        }
    }
    System.out.println(count);
}
}


我算为2,希望这会有所帮助。

08-03 12:18