I've to make a program to find the frequency of different words in a string that may contain spaces in sorted way. like if I've string
"dsaa wbaa sc" the output must be:
4a 1c 1d 2s 1w
Counting different word frequency in a string using c++?
Here you go:
#include%26lt;iostream%26gt;
using namespace std;
int main()
{
int alp[25]; //for 26 alphabets
int j;
for(j=0;j%26lt;26;j++)
alp[j]=0;
char str[20];
cout%26lt;%26lt;"Enter a string of max 20 char: ";
cin.getline(str,20);
int i;
for(i=0;i%26lt;strlen(str);i++)
{
if(str[i] != ' ')
++alp[str[i] - 'a'];
}
for(i=0;i%26lt;26;i++)
{
if(alp[i] != 0)
cout%26lt;%26lt;alp[i]%26lt;%26lt;(char)('a'+i)%26lt;%26lt;" ";
}
free(str);
return 0;
}
Hope this helps!
Reply:You can do this pretty easily using the STL map data-structure.
example accumulator
std::map%26lt;std::string, int%26gt; count = std::map%26lt;std::string,int%26gt;()
std::string tmpStr;
while(/* there is input */){
/*read tmpStr */
count[ tmpStr ]++;
}
...
output
std::cout %26lt;%26lt; String %26lt;%26lt; "\t" %26lt;%26lt; Count %26lt;%26lt; std::endl;
for (std::map%26lt;%26lt;:std::string, int%26gt;::iterator it = count.begin(); it != count.end(); ++i){
std::cout %26lt;%26lt; it-%26gt;first %26lt;%26lt; "\t" %26lt;%26lt; it-%26gt;second %26lt;%26lt; std::endl;
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment