Count no. the appearance of the exact word in the file using java

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.

+4
3

:

Pattern.compile("\\bhell\\b");
+5

"\\ b" :

  int matches = 0;  
  Matcher matcher = Pattern.compile("\\bhell\\b", Pattern.CASE_SENSITIVE).matcher(str);
  while (matcher.find()) matches++;
+5

Try

String str = "put the string to be searched here";
Scanner sc = new Scanner(str);
String search = "put the string you are searching here";
int counter = 0; //this will count the number of occurences
while (sc.hasNext())
{
if (sc.next() == search)
counter++;
}

Since sc.next () reads the full next token, it will be hell and hi will not bother you.

+1
source

All Articles