Tuesday 19 February 2013

To count the number of occurences of characters in a sentence



#include<iostream>
#include<conio.h>
#include<cstring>
#include<string>
using namespace std;
int main()
{string a;
cout<<"enter some text :\n\n";
getline(cin,a);

int l=a.length(),c=1,j,k,i,m;    //c for counting the number of occourences which is stored in freq
int freq[l];
for(j=0;j<l;j++)
   {freq[j]=c;
      for( k=j+1;k<l;k++)
       {   if(a[j]==a[k])              //a[j]  is compared with all of the remaining of characters, if
            {freq[j]=++c;              //it is equal to any of the character , count of freq[j]
            for( m=k;m<l-1;m++)   //corresponding to a[j] is increased.a[k] equal to a[j] is            
            a[m]=a[m+1];               // replaced by a[k+1].similarly a[k+1] by a[k+2].... so on
            k--;l--;
            }
        }c=1;
   }

 cout<<"character\tFrequency\n";
 for(i=0;i<l;i++)
 cout<<a[i]<<"\t\t"<<freq[i]<<endl;


 getch();
 return 0;
}

No comments:

Post a Comment