How To Write A C++ Program To Count Number Of Occurrence Of Each Word In A Given Strings

c[1]

 

C++ is one of the most popular language in the world. Almost in every university students start learning coding in C++. How Strings present one of the most commonly asked question in C++ assignment for its students.

Following is the simple code written in C++ to find occurrence of each and every word in a given string or sentence from any user.

EXAMPLE OUTPUT:

Enter Any String: How Strings Tech How Strings

How : 2 Times

Strings : 2 Times

Tech : 1 Time

 

CODE:

//Program to find the frequency of words in an array

#include <iostream>
using namespace std;
#include <conio.h>
#include<cstring>
int main()
{
int count = 0, c = 0, i, j = 0, k, space = 0;

char str[500], p[500][500], str2[500][500], copyall[500][500];

cout<<“Enter any string string: “; //Inputting the string
cin.getline(str, 500);

cout<<endl; //Just for better display

//Module#1
i = 0;
while ( str[i] != ‘\0’ ) //To count spaces in given string
{
if (str[i] == ‘ ‘)
{
space++;
}
i++;
}

cout<<space; //Module#2

i = 0, j = 0, k = 0;
while( str[j]!=’\0’) //Copying all words from orignall 1D array (str[]) into 2D array (p[][]) such that each word is copied row by row in p[][]
{
if (str[j] == ‘ ‘)
{
p[i][k] = ‘\0’;
i++;
k = 0;
}
else
p[i][k++] = str[j];
j++;
}

//Module#3

k = 0;
for (i = 0;i <= space;i++) //This mechanism is “basically” copying data from 2D array p[][] into another 2D array Str2[][] the same way as it has in itself
{
j = 0;
while(j <= space)
{
if (i == j)
{
strcpy(str2[k], p[i]);
k++;
count++;
break;
}
else
{
if (strcmp(str2[j], p[i]) != 0)
{
j++;
continue;
}

else
break;
}

}
}

//Module#4

for (i = 0;i < count;i++) //Now comparing each word of str2[][] to all the words of p[][] and counting how many times that word appears {Both 2D arrays have same data. In 2D form it makes easy to compare and count}
{
j = 0;
while(j <= space)
{
if (strcmp(str2[i], p[j]) == 0)
c++;
j++;
}

/*
//declare array of type integer
char a[500],i,j,temp;

//sort the array
for(i=0;i<10;i++)
{
for(j=0;j<10;j++)
{
if(a[i]<a[j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
//Print the array.
for(i=0;i<10;i++)
cout<<a[i]<<endl;

}
*/
cout<< str2[i]<<” -> “<< c <<” times\n”<<endl;

c = 0; //c is the counter to count how many times each word is appeared
}

cout<<endl<<endl;

return 0;
}
//End

Write in below comments if you have any tutorial request or have any assignment pending from your college.

Facebook Comments

Leave a Reply

Your email address will not be published. Required fields are marked *