3 Techniques to Count Occurrences of a Word in a String

count a word occurrences in a string

Quick summary

In this tutorial, we will write a java program that will count the occurrences of a word in a string. Also, we will check three different methods to solve this problem.

The String is of a group of words or characters. The aim of the program is to find the given word and count how many times it occurs in the content string.

Example:
Input: string = "Timearrows is computer programing blog"
Find string = "blog"
Output: Hello = 1

Input: string = "Timearrows is computer programing blog"
Find string = "web"
Output: Hello = 0

#1. Using HashMap

In this method, we will use the HashMap collection. The HashMap stores data in key-value pairs.

So, we will store the substring as a key and its count as a value in the HashMap. With this HashMap, we can also print all occurrences of all words from the content.

Approach:

  • Split the string by space and assign it to contentArray.
  • Create a Map collection object.
  • Loop through the contentArray.
  • In the first iteration, the map is empty. Put string st from the iteration into the map as key and add 1 as value.
  • In every true condition update string st in key and increase the count by 1 as a value.ยท  Use stream API filter for iteration.
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
 
public class CountWords {
    
 	/**
 	 *
 	 * @param word
 	 * @param content
 	 */
 	public static void countWord(String word, String content) {
         
      	//Check the string content and find are not null or empty
      	if((!Objects.isNull(content) && !(" ").equals(content)) && (!Objects.isNull(word) && !(" ").equals(word))){
         
           	//Split the string content by space
           	String[] contentArray = content.split(" ");
              
           	//Create hashmap to store substring and count
           	Map<String, Integer> map = new HashMap<>();
              
           	//Loop the contentArray
           	for(String st : contentArray) {
                    
                 	//If match found increase count by 1
                 	if(map.containsKey(st)) {
                      	map.put(st, map.get(st) + 1);
                 	}else {
                      	map.put(st, 1);
                 	}   
           	}
              
           	//If map contain given word than display count
           	if(map.containsKey(word)) {
    			System.out.println(word + " occur " + map.get(word) + " times");
    		}else {
    			System.out.println(word + " occur 0 times");
    		}
              
      	} else {
           	System.out.println("Invalid string passed");
      	}        
 	}
    
    
 	/**
 	 *
 	 * @param args
 	 */
 	public static void main(String[] args) {
      	String content = "Hello world hello world hello world hello Apple Apple Apple Apple";
      	String word = "world";
         
      	countWord(word, content);
         
 	}
 
}
blog occur 1 times

#2. Using Stream Filter API:

In this method, we will use java 8 new feature stream API  to count the occurrences of the word in the string.
The filter method is an intermediate operation in-stream API. it will filter stream elements based on a given predicate.

Approach:

  • Split the given content string by space and assign it to sArray.
  • Find the count of given words in the string using the stream filter method. 
  • count() – a terminal operational method to count the word occurrences. 
  • Print the word and its count.
import java.util.Arrays;
import java.util.Objects;

public class WordOccurence {
	
	public static void countWord(String word, String content) {
		if((Objects.nonNull(word) && !(" ").equals(word)) && (Objects.nonNull(content) && !(" ").equals(content))){
			String[] sArray = content.split(" ");
			long l = Arrays.asList(sArray).stream().filter(d -> d.equals(word)).count();
			System.out.println(word +" occur "+ l + " times");
		}else {
			System.out.println("Invalid string");
		}
	}
	
	public static void main(String[] args) {
		String content ="Timearrows is a programming     and tutorials blog and it teaches webdevelopment";
		String word = " ";
		countWord(word, content);
		
	}

}
blog occur 1 times

#3. Using Array

Approach :

  • Split the string by space and assign it to contentArray.
  • Loop the contentArray.
  • Get count=0 variable, in every true condition increase count value by 1.
  • Print the given word and count.
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
 
public class CountWords {
    
    
    
 	/**
 	 *
 	 * @param word
 	 * @param contnet
 	 */
    
 	public static void findWord(String word, String contnet) {
         
      	int count = 0;
      	String[] contentArray = contnet.split(" ");
         
      	for(int i =0 ; i< contentArray.length; i++) {
           	if(contentArray[i].equals(word))
                 	count++;
      	}
         
      	System.out.println(word + " occur " + count +" times");
         
         
 	}
    
    
 	/**
 	 *
 	 * @param args
 	 */
 	public static void main(String[] args) {
      	String content = "Timearrows a programming blog for all programmers";
      	String word = "programmers";
         
      	countWord(word, content);
      	findWord(word, content);
         
 	}
 
}
blog occur 1 times

Conclusion:

In this tutorial, we have written 3 different methods such as java 8 new feature – stream API, map collection, and simple array to count occurrences of a word in a given string.

Please comment your suggestion in the comment box below.

Recommended:

Leave A Reply

Your email address will not be published.