Reputation: 1
my task at hand was to add an event to a Jbutton that will count the number of occurrences of a word displayed in a JTextArea. The codes are as shown below but this counts everyword;
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 ");
}
}
help me figure out how to perform word count for a specific word such as "Jeff" when it is entered in the JTextArea.thanks
Upvotes: 0
Views: 1521
Reputation: 873
try like this,
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);
I have tried this code
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);
}
}
i got count as 2, hope this will help.
Upvotes: 1
Reputation: 328
If you want to count no.of words,exactly a word, but not in middle of any word, then your job is too easy. Just split the text which you get from JTextArea, where you will get an array of words in your text(which is entered through TextArea). From that array you can iterate using for loop and compare the word with the array items and inside the loop increment the count
that's it.
If you wanted to count the occurrences, where the word might be embedded inside another word, then your job is some what tough. For this, you need to know Regular Expressions
Upvotes: 0