Reputation: 455
I have a problem when I try to count how many times a word appears in a TXT file.
When I select the file, the content of the file is displayed in area. Then I enter the word in txta to search. I then click the btn, but the code does not work.
public int contarPalabras(String chain, String word) {
// English translation:
// Receive a string and a word and return the amount of times
// that the word was found in the string.
// If the letter is not found, return (-1).
int cant = 0;
int intIndex = chain.indexOf(word);
if (intIndex == -1) {
cant = -1;
} else {
cant = intIndex;
}
return cant;
}
Upvotes: 1
Views: 4786
Reputation: 17764
Read the documentation of String.indexOf(string)
. It does not do what you think it does. It returns only the index of first occurrence of the parameter.
In order to get it work you can do something like this:
public int countWord(String chain, String word){
if("".equal(word)){
throw new IllegalArgumentException("word is empty string"); // error when word is empty string
}
index = 0;
count = 0;
while (index != -1){
int found = chain.indexOf(word, index);
if(found != -1){
count++;
index = found + word.length();
}
}
return count;
}
EDIT
If you really just want to count complete words (that is substrings separated by spaces from both sides) this version will be more useful:
public int countWord(String chain, String word){
if("".equal(word)){
throw new IllegalArgumentException("word is empty string"); // error when word is empty string
}
index = 0;
count = 0;
word = " " + word + " ";
while (index != -1){
int found = chain.indexOf(word, index);
if(found != -1){
count++;
index = found + word.length() - 1;
}
}
return count;
}
Upvotes: 3
Reputation: 106
I think the 2 answers given will have the following problem: in the text: "Saturdays and Sundays are my favourite days" if you seach for "days", it will return: 3 because it will match Satur days, Sun days and days. I assume you want to match only days
In that case you have to use regex, here is the answer:
public int countWord(String chain, String word){
Pattern p = Pattern.compile("\\b" + word + "\\b");
Matcher m = p.matcher(chain);
int count = 0;
while(m.find()) {
count++;
}
return count;
}
Upvotes: 0
Reputation: 597046
commons-lang has StringUtils.countMatches(str, sub)
which does exactly what you want.
Upvotes: 4