Java JTextArea中的特定字数

Java JTextArea中的特定字数,java,swing,Java,Swing,我手头的任务是向Jbutton添加一个事件,该事件将统计JTextArea中显示的单词出现的次数。代码如下所示,但每个字都计算在内 private void btnCountActionPerformed(java.awt.event.ActionEvent evt) { if(!(txtaInput.getText().trim().length()==0)){ String a = St

我手头的任务是向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,希望这会有所帮助。

如果你想计算单词的数量,准确地说是一个单词,但不在任何单词的中间,那么你的工作太简单了。 只需拆分从JTextArea获得的文本,在那里您将在文本中获得一个单词数组(通过TextArea输入)。从该数组中,您可以使用for循环进行迭代,并将单词与数组项进行比较,然后在循环中增加计数

就这样


如果你想计算单词可能嵌入到另一个单词中的出现次数,那么你的工作就有点困难了。为此,您需要知道正则表达式

如果我理解您的意思,您必须迭代文本区域中的所有文本,并检查您的单词是否与文本区域中的“I”单词相等。如果是你增加你的计数器。Ulaga给出了我描述的第一种情况的精确代码。如果您想将解决方案作为第二个解决方案,则必须了解正则表达式。尝试此方法后,计数对于字母计数非常有效,例如“String StringToFind=“a”.toLowerCase();”但对于单词计数,无论单词出现的次数多少,响应都会给出零(0)计数。