I have a requirement in which I have to find no. time, a specific word appears in the file. For instance,
String str = "Hi hello how are you. hell and heaven. hell, gjh, hello,sdnc ";
Now on this line I want to count no. once the word "hell" appeared. The account should include “hell”, “hell”, all these words, but not “hello”. Therefore, according to this line, I want the number to be 2.
I used the following approaches
the first:
int match = StringUtils.countMatches(str, "hell");
StringUtils has an org.apache.commons.lang3 library
second:
int count = 0;
Pattern p = Pattern.compile("hell");
Matcher m = p.matcher(str);
while (m.find()) {
count++;
}
third
int count =0;
String[] s = str.split(" ");
for(String word: s)
if(word.equals("hell")
count++;
the first two approaches gave 4 as an answer, and the third approach gave 1 as an answer.
Please suggest anyway when I can get 2 as an answer and fill out my request.