#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
CodePudding user response:
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
CodePudding user response:
Another option to add to @codeling's answer. Same idea, but different implementation:
- You can use an array to count the used letters. First array position will tell you number of appearances for 'a', second position for 'b' and so on.
- You could extend it to count uppercase and symbols.
- You could also change the
std::array
for asize_t counts[26]
array.
#include <array>
#include <iostream> // cout
#include <string>
int main()
{
const std::string s{"aaabbc"};
std::array<size_t, 26> counts{};
for (auto&& ch : s)
{
if (ch >='a' and ch <= 'z')
{
counts[ch - 'a'] ;
}
}
for (char i{0}; i < counts.size(); i)
{
if (counts[i])
{
std::cout << static_cast<char>('a' i) << ": " << counts[i] << "\n";
}
}
}