WAP To Print Frequency Of Words In A String

Print Frequency Of Words In A String: In this blog post, we’ll explore a fascinating challenge: writing a program to print the frequency of words in a string. Understanding how to efficiently count the occurrences of words within a given text opens up a realm of possibilities for text processing, data analysis, and natural language processing applications.

We’ll embark on a step-by-step exploration of the problem, catering to programmers of all levels, from beginners to experienced developers.

Our mission is to equip you with the knowledge and skills to create a robust and elegant solution to this problem. We’ll cover fundamental concepts like data structures, iteration, and algorithm design, providing you with the tools needed to tackle complex text analysis tasks. Throughout this journey, we’ll use Java as our programming language of choice, leveraging its versatility and ease of use.

Whether you’re an aspiring developer eager to learn more about string manipulation or an experienced coder seeking to hone your algorithmic skills, this blog post series is tailored for you. So, let’s begin our exciting journey into counting word frequencies in a string and unravel the mysteries of text analysis. Are you ready to dive in? Let’s get started!

package com.softwaretestingo.interviewprograms;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Map;
import java.util.TreeMap;
public class InterviewPrograms97 
{
	//Write a program to print the frequency of words in a paragraph
	private static void countfreqword(String str) 
	{
		Map<String,Integer> mp=new TreeMap<>();
		String arr[]=str.split(" ");

		for(int i=0;i<arr.length;i++)
		{
			if(mp.containsKey(arr[i]))
			{
				mp.put(arr[i], mp.get(arr[i])+1);
			}
			else
			{
				mp.put(arr[i],1);
			}
		}

		for(Map.Entry<String,Integer> entry:mp.entrySet())
		{
			System.out.println(entry.getKey()+" - "+entry.getValue());
		}
	}
	public static void main(String[] args) throws IOException 
	{
		String str;

		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		System.out.println("Enter the string");
		str=br.readLine();

		countfreqword(str);
	}
}

Output

Enter the string
Software Testingo Blog Software Best Blog
Best - 1
Blog - 2
Software - 2
Testingo - 1

This Java program accomplishes the task of printing the frequency of words in a given paragraph. Let’s walk through the code step by step to help Java beginners understand it:

  • Import Statements: The program starts with import statements to include necessary classes from the Java standard library. It imports BufferedReader, IOException, InputStreamReader, Map, and TreeMap.
  • Class and Method Declaration: The program defines a class named InterviewPrograms97. Inside the class, there is a private static method countfreqword, responsible for counting the frequency of words in the input paragraph. The main method serves as the entry point of the program.
  • countfreqword Method: This method takes a single parameter str, which represents the input paragraph to be analyzed for word frequency. Inside the method, a TreeMap named mp is created to store the words as keys and their respective frequencies as values. A TreeMap is used to automatically sort the keys in ascending order.
  • Splitting the Paragraph: The input paragraph is split into words using str.split(” “). This divides the paragraph into an array of words based on space as the delimiter, and the array is stored in the arr variable.
  • Counting Word Frequencies: The method then iterates through the arr array, and for each word, it checks if it already exists in the mp map. If the word is already present, its frequency is incremented by 1. If the word is not present, it is added to the map with a frequency of 1.
  • Printing the Frequency: After counting the frequencies, the method iterates through the mp map using a for-each loop and prints each word along with its corresponding frequency using System.out.println().
  • User Input: In the main method, the program prompts the user to enter a paragraph using System.out.println(). The user’s input is obtained using a BufferedReader, which reads input from the console. The input paragraph is then stored in the str variable.
  • Output: The countfreqword method is called with the input paragraph str, and it processes the paragraph, printing the word frequencies.

In summary, this program provides a powerful tool to analyze and understand the frequency of words in a given paragraph. It efficiently counts the occurrences of each word and prints the results in ascending order. By studying this code, Java beginners can learn about maps, loops, and string manipulation in Java and enhance their programming skills in handling textual data.

Alternative Way 1:

package com.softwaretestingo.interviewprograms;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class InterviewPrograms97_1 
{
	//Write a program to print the frequency of specific words in a paragraph
	public static void main(String[] args) throws IOException 
	{
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		System.out.println("Enter the String: ");
		String s=br.readLine();
		System.out.println("Enter substring: ");
		String sub=br.readLine();
		int ind,count=0;
		for(int i=0; i+sub.length()<=s.length(); i++)    //i+sub.length() is used to reduce comparisions
		{
			ind=s.indexOf(sub,i);
			if(ind>=0)
			{
				count++;
				i=ind;
				ind=-1;
			}
		}
		System.out.println("Occurence of '"+sub+"' in String is "+count);
	}
}

Output

Enter the String: 
Welcome To the Software Testing Blog Called SoftwareTestingo
Enter substring: 
Software
Occurence of 'Software' in String is 2

This Java program is designed to print the frequency of a specific word (substring) in a given paragraph. Let’s walk through the code step by step:

  • Import Statements: The program begins without any import statements, as it does not require any external classes from the Java standard library.
  • Class and Method Declaration: The program defines a class named InterviewPrograms97_1. Inside the class, the main method serves as the entry point of the program.
  • User Input: In the main method, the program prompts the user to enter a paragraph using System.out.println(). The user’s input is obtained using a BufferedReader, which reads input from the console. The input paragraph is stored in the s variable.The program also prompts the user to enter a specific word (substring) to find its frequency in the paragraph. The input substring is stored in the sub variable.
  • Counting Word Frequency: The program then uses a loop to search for occurrences of the input substring within the paragraph. The loop starts from i = 0 and continues until i + sub.length() <= s.length(). The reason for using i + sub.length() in the loop condition is to reduce unnecessary comparisons beyond the possible substring boundaries.Inside the loop, the program uses the indexOf method of the String class to find the first occurrence of the substring in the paragraph, starting from index i. If a match is found (i.e., ind >= 0), the program increments the count variable and updates the loop’s index i to the index of the found substring (i.e., i = ind). This avoids counting the same occurrence multiple times.
  • Output: After counting the frequency, the program displays the number of occurrences of the input substring in the paragraph using System.out.println().

In essence, this program provides a simple and efficient way to find the frequency of a specific word (substring) in a given paragraph. It showcases how to search for substrings using the indexOf method and handle loop iterations optimally to count occurrences accurately. Java beginners can learn from this code how to work with strings, loops, and conditional statements to perform useful text analysis tasks. Happy coding!

I love open-source technologies and am very passionate about software development. I like to share my knowledge with others, especially on technology that's why I have given all the examples as simple as possible to understand for beginners. All the code posted on my blog is developed, compiled, and tested in my development environment. If you find any mistakes or bugs, Please drop an email to softwaretestingo.com@gmail.com, or You can join me on Linkedin.

Leave a Comment