我的任务是向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.thanks中输入特定单词(例如“Jeff”)时执行单词计数
答案 0 :(得分:1)
尝试这样,
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,希望这会有所帮助。
答案 1 :(得分:0)
如果你想计算任何单词,一个单词,但不是任何单词的中间,那么你的工作就太容易了。 只需拆分从JTextArea获得的文本,您将在文本中获得一系列单词(通过TextArea输入)。从该数组中,您可以使用 for 循环进行迭代,并将该单词与数组项进行比较,并在循环内增加计数
就是这样。
如果你想计算出现的位置,这个词可能嵌入另一个单词中,那么你的工作就是艰难的。为此,您需要知道正则表达式