Calculate the frequency of each word in the given string
Last Updated :
02 Mar, 2023
Given a string str, the task is to find the frequency of each word in a string.
Examples:
Input: str = “Geeks For Geeks”
Output:
For 1
Geeks 2
Explanation:
For occurs 1 time and Geeks 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++
#include <bits/stdc++.h>
using namespace std;
void printFrequency(string str)
{
map<string, int > M;
string word = "" ;
for ( int i = 0; i < str.size(); i++) {
if (str[i] == ' ' ) {
if (M.find(word) == M.end()) {
M.insert(make_pair(word, 1));
word = "" ;
}
else {
M[word]++;
word = "" ;
}
}
else
word += str[i];
}
if (M.find(word) == M.end())
M.insert(make_pair(word, 1));
else
M[word]++;
for ( auto & it : M) {
cout << it.first << " - "
<< it.second
<< endl;
}
}
int main()
{
string str = "Geeks For Geeks" ;
printFrequency(str);
return 0;
}
|
Java
import java.util.Map;
import java.util.TreeMap;
public class Frequency_Of_String_Words {
static void count_freq(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) {
String str = "Geeks For Geeks" ;
count_freq(str);
}
}
|
Python3
def printFrequency(strr):
M = {}
word = ""
for i in range ( len (strr)):
if (strr[i] = = ' ' ):
if (word not in M):
M[word] = 1
word = ""
else :
M[word] + = 1
word = ""
else :
word + = strr[i]
if (word not in M):
M[word] = 1
else :
M[word] + = 1
for it in M:
print (it, "-" , M[it])
strr = "Geeks For Geeks"
printFrequency(strr)
|
C#
using System;
using System.Collections.Generic;
class GFG{
static void count_freq(String str)
{
SortedDictionary<String,
int > mp = new SortedDictionary<String,
int >();
String []arr = str.Split( ' ' );
for ( int i = 0; i < arr.Length; i++)
{
if (mp.ContainsKey(arr[i]))
{
mp[arr[i]] = mp[arr[i]] + 1;
}
else
{
mp.Add(arr[i], 1);
}
}
foreach (KeyValuePair<String, int > entry in mp)
{
Console.WriteLine(entry.Key + " - " +
entry.Value);
}
}
public static void Main(String[] args)
{
String str = "Geeks For Geeks" ;
count_freq(str);
}
}
|
Javascript
function printFrequency(str) {
let M = new Map();
let word = "" ;
for (let i = 0; i < str.length; i++) {
if (str[i] === " " ) {
if (!M.has(word)) {
M.set(word, 1);
word = "" ;
}
else {
M.set(word, M.get(word) + 1);
word = "" ;
}
}
else {
word += str[i];
}
}
if (!M.has(word)) {
M.set(word, 1);
} else {
M.set(word, M.get(word) + 1);
}
M = new Map([...M.entries()].sort());
for (let [key, value] of M) {
console.log(`${key} - ${value}`);
}
}
let str = "Geeks For Geeks" ;
printFrequency(str);
|
Output:
For - 1
Geeks - 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.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...