#include<iostream>
using namespace std;
void check_exist_get_count(string str,char ch)
{
int counter=0;
for(int x=0;x<str.length();x++)
{
if(str[x]==ch)
counter++;
}
cout<<ch<<" : "<<counter;
}
int main ()
{
string str;
cin>>str;
for(int x=0;x<str.length();x++)
{
check_exist_get_count(str,str[x]);
}
return 0;
}
Without built in function i need to to count the occurence of letter but i have problem what condition i should use to check which make for loop not sending letter more than one time
example:in my code i get
input
aaabbc
output
a : 3 a : 3 a : 3 b : 2 b : 2 c : 1
but Required answer should be
a : 3 b : 2 c : 1
>Solution :
You’re just iterating over the string once in your main function, and for every character in that string, again go over the whole string and count how many characters like that are in there.
What you don’t do is track which characters you already have counted, that’s why you count them multiple times. Don’t nest loops (calling your function inside the first loop), but tear those things apart:
One option would be to do a first pass over the string, in which you just build a list of characters that are in the string, something like this:
std::set<char> chars;
for (char c: str)
{
chars.insert(c); // a set doesn't allow duplicate entries
// so you don't have to check yourself if it's already in there
}
Then you could, in a second loop, call count for each of the characters in the set. That would still be inefficient, though; you can use a map for keeping track what characters are as well as their count so far. Something like this:
Code to compute the histogram of character frequencies then could look something like this:
#include <iostream>
#include <map>
#include <string>
int main ()
{
std::string str("aaabbc");
std::map<char, size_t> charHistogram;
for (char c: str)
{
if (charHistogram.find(c) == charHistogram.end())
{
charHistogram[c] = 0;
}
++charHistogram[c];
}
for (auto const & p: charHistogram)
{
std::cout << p.first << " : " << p.second << " ";
}
return 0;
}
See code in cpp.sh