Calculate the frequency of each word in the given string
Given a string str, the task is to find the frequency of each word in a string.
Examples:
Input: str = “Beginner For Beginner”
Output:
For 1
Beginner 2
Explanation:
For occurs 1 time and Beginner occurs 2 times in the given string str.Input: str = “learning to code is learning to create and innovate”
Output:
and 1
code 1
create 1
innovate 1
is 1
learning 2
to 2
Explanation:
The words and, code, create, innovate, is occurs 1 time; and learning, to occurs 2 times in the given string str.
Approach: To solve the problem mentioned above we have to follow the steps given below:
- Use a Map data structure to store the occurrence of each word in the string.
- Traverse the entire string and check whether the current word is present in map or not. If it is present, then update the frequency of the current word else insert the word with frequency 1.
- Traverse in the map and print the frequency of each word.
Below is the implementation of the above approach:
C++
// C++ program to calculate the frequency // of each word in the given string #include <bits/stdc++.h> using namespace std; // Function to print frequency of each word void printFrequency(string str) { map<string, int > M; // String for storing the words string word = "" ; for ( int i = 0; i < str.size(); i++) { // Check if current character // is blank space then it // means we have got one word if (str[i] == ' ' ) { // If the current word // is not found then insert // current word with frequency 1 if (M.find(word) == M.end()) { M.insert(make_pair(word, 1)); word = "" ; } // update the frequency else { M[word]++; word = "" ; } } else word += str[i]; } // Storing the last word of the string if (M.find(word) == M.end()) M.insert(make_pair(word, 1)); // Update the frequency else M[word]++; // Traverse the map // to print the frequency for ( auto & it : M) { cout << it.first << " - " << it.second << endl; } } // Driver Code int main() { string str = "Beginner For Beginner" ; printFrequency(str); return 0; } |
Java
// Java implementation of the above // approach import java.util.Map; import java.util.TreeMap; public class Frequency_Of_String_Words { // Function to count frequency of // words in the given string static void count_freq(String str) { Map<String,Integer> mp= new TreeMap<>(); // Splitting to find the word String arr[]=str.split( " " ); // Loop to iterate over the words for ( int i= 0 ;i<arr.length;i++) { // Condition to check if the // array element is present // the hash-map if (mp.containsKey(arr[i])) { mp.put(arr[i], mp.get(arr[i])+ 1 ); } else { mp.put(arr[i], 1 ); } } // Loop to iterate over the // elements of the map for (Map.Entry<String,Integer> entry: mp.entrySet()) { System.out.println(entry.getKey()+ " - " +entry.getValue()); } } // Driver Code public static void main(String[] args) { String str = "Beginner For Beginner" ; // Function Call count_freq(str); } } |
Python3
# Python3 program to calculate the frequency # of each word in the given string # Function to print frequency of each word def printFrequency(strr): M = {} # string for storing the words word = "" for i in range ( len (strr)): # Check if current character # is blank space then it # means we have got one word if (strr[i] = = ' ' ): # If the current word # is not found then insert # current word with frequency 1 if (word not in M): M[word] = 1 word = "" # update the frequency else : M[word] + = 1 word = "" else : word + = strr[i] # Storing the last word of the string if (word not in M): M[word] = 1 # Update the frequency else : M[word] + = 1 # Traverse the map # to print the frequency for it in M: print (it, "-" , M[it]) # Driver Code strr = "Beginner For Beginner" printFrequency(strr) # This code is contributed by shubhamsingh10 |
C#
// C# implementation of the above // approach using System; using System.Collections.Generic; class GFG{ // Function to count frequency of // words in the given string static void count_freq(String str) { SortedDictionary<String, int > mp = new SortedDictionary<String, int >(); // Splitting to find the word String []arr = str.Split( ' ' ); // Loop to iterate over the words for ( int i = 0; i < arr.Length; i++) { // Condition to check if the // array element is present // the hash-map if (mp.ContainsKey(arr[i])) { mp[arr[i]] = mp[arr[i]] + 1; } else { mp.Add(arr[i], 1); } } // Loop to iterate over the // elements of the map foreach (KeyValuePair<String, int > entry in mp) { Console.WriteLine(entry.Key + " - " + entry.Value); } } // Driver Code public static void Main(String[] args) { String str = "Beginner For Beginner" ; // Function call count_freq(str); } } // This code is contributed by Rajput-Ji |
Javascript
//Javascript code for above // Function to print frequency of each word function printFrequency(str) { // Create a new Map to store the frequency counts let M = new Map(); // String for storing the words let word = "" ; // Loop through each character in the string for (let i = 0; i < str.length; i++) { // Check if current character is a blank space if (str[i] === " " ) { // If the current word is not found then insert it // into the Map with frequency 1 if (!M.has(word)) { M.set(word, 1); word = "" ; } // If the current word is already in the Map, update its frequency count else { M.set(word, M.get(word) + 1); word = "" ; } } // If the current character is not a blank space, // add it to the current word else { word += str[i]; } } // Check if the last word in the string is already in the Map, // and update its frequency count if it is if (!M.has(word)) { M.set(word, 1); } else { M.set(word, M.get(word) + 1); } // sorting map key in increasing order M = new Map([...M.entries()].sort()); // Loop through each key-value pair in the Map and // print the frequency count of each word for (let [key, value] of M) { console.log(`${key} - ${value}`); } } // Driver Code let str = "Beginner For Beginner" ; printFrequency(str); |
For - 1 Beginner - 2
Time Complexity: O(L * log (M)) , Where L is the length of the string and M is the number of words present in the string.
Auxiliary Space: O(M), where M is the number of words present in the string.
Contact Us