Search code examples
javafrequencywords

how do i count occurrence of words in a line


I am fairly new to java. I want to count the occurrences of words in a particular line. So far i can only count the words but no idea how to count occurrences.

Is there a simple way to do this?

Scanner file = new Scanner(new FileInputStream("/../output.txt"));
int count = 0;
  while (file.hasNextLine()) {
    String s = file.nextLine();
    count++;    
      if(s.contains("#AVFC")){
       System.out.printf("There are %d words on this line ", s.split("\\s").length-1);
       System.out.println(count);   
      }

  }
file.close(); 

Output:

    There are 4 words on this line 1

    There are 8 words on this line 13

    There are 3 words on this line 16

Solution

  • Simplest way I can think of is to use String.split("\\s"), which will split based on spaces.

    Then have a HashMap containing a word as the key with the value being the number of times it is used.

       HashMap<String, Integer> mapOfWords = new HashMap<String, Integer>();
    
          while (file.hasNextLine()) {
            String s = file.nextLine(); 
            String[] words = s.split("\\s");
            int count;
            for (String word : words) {
               if (mapOfWords.get(word) == null) {
                  mapOfWords.put(word, 1);
               }
               else {
                  count = mapOfWord.get(word);
                  mapOfWords.put(word, count + 1);
               }
            }
          }
    

    Implementation you requested to skip strings that contain certain words

       HashMap<String, Integer> mapOfWords = new HashMap<String, Integer>();
    
       while (file.hasNextLine()) {
            String s = file.nextLine(); 
            String[] words = s.split("\\s");
            int count;
    
            if (isStringWanted(s) == false) {
               continue;  
            } 
    
            for (String word : words) {
               if (mapOfWords.get(word) == null) {
                  mapOfWords.put(word, 1);
               }
               else {
                  count = mapOfWord.get(word);
                  mapOfWords.put(word, count + 1);
               }
            }
          }
    
    private boolean isStringWanted(String s) {
        String[] checkStrings = new String[] {"chelsea", "Liverpool", "#LFC"};
    
        for (String check : checkString) {
            if (s.contains(check)) {
               return false;
            }
        }
        return true;
    }