CodeX
CodeX

Reputation: 135

Counting the occurrence of a word in a string in Java

I read a word from the user (query) I show the number of occurrences of that word in each line of a given textfile

Sample text file:

cat

cat dog cat

cat

if I search on cat .. the occurences I get are 1, 2, and 3 .. 3 is wrong..

so any help to fix the counter??

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;


public class main {


public static void main(String[] args) throws FileNotFoundException  {
    

    System.out.println("Search: ");
    String query = ToRead();
    int counter =0;
    int lineNumber=0;
    int k=0;

    System.out.println("Searching for"+ " " + query);
    
    File file = new File("C:/Users/IBM_ADMIN/Desktop/test.txt");
    Scanner scanner=new Scanner(file);
    //List<String> list=new ArrayList<>();
     
    while(scanner.hasNextLine())
    {
        counter=0;
         
        String line = scanner.nextLine();
        
        System.out.println("line " + lineNumber + " :" + line);
        
        int result = line.indexOf(query); 
        while(result !=-1) 
        { 
            result = line.indexOf(line,result+1); 
            counter++; 
        } 
        System.out.println(counter);
                    
        //System.out.println("The string occurred "+counter+" times");           
        
        lineNumber++;           
    }   
}

public static String ToRead()
{
    String s;
    Scanner in = new Scanner(System.in);
    s = in.nextLine();
    return s;
}   

}

Upvotes: 1

Views: 182

Answers (5)

floyd
floyd

Reputation: 702

Another way to count number of occurrences of string is to use splitmethod(http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split%28java.lang.String%29):

int numberOfOccurrences = split("find me", -1).length - 1;

Upvotes: 2

Buurman
Buurman

Reputation: 1984

First, change your inner loop to

int result = line.indexOf(query); 
while(result !=-1) 
{ 
     counter++;
     result = line.indexOf(query,result+1); 
} 
System.out.println(counter);

Second, can you give the current output of your program and your expected output?

Upvotes: 0

Lajos Arpad
Lajos Arpad

Reputation: 76426

You can use StringUtils.countMatches, like this:

count += StringUtils.countMatches(line, query);

If you want to print out the numbers in each line, then

count = StringUtils.countMatches(line, query);

I do not understand your problem exactly. If you want to print out all the occurrences line-by-line, then the second should be used. Otherwise, the first should be used, but with the println outside the loop.

Upvotes: 0

Bathsheba
Bathsheba

Reputation: 234645

You should only increment counter if result is not -1.

In your while loop you are incrementing it once more, even if result is -1.

Upvotes: -1

Armando Zavala
Armando Zavala

Reputation: 49

What if you reset the counter right after you print out your answer? So under your print line just set the counter to zero. That will make sure you change or reset it. Hope it helps but I have no way to test it out at the moment.

Upvotes: 0

Related Questions