I have a problem when I try to count how many times a word appears in a TXT file.
- I create a textfield ( txta )
- I create a button to apply the action ( btn )
- I create a textarea ( area ) where the content of the file is displayed
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;
}
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:
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: