In this post we will try to find out the frequency(count) of each character in a given string.
Method1:
Prerequisites: Basic knowledge of array, string and ASCII value.
let's talk about the question:
We have a string of either lowercase or uppercase characters. that means string must have all characters from lowercase or uppercase:
eg:"earth", "EARTH"
Now we have to find the frequency(count) of each character of the given string;
eg:"babsur"
freq of "a" = 1;
freq of "b" = 2;
freq of "r" =1;
freq of "s" = 1;
freq of "u" = 1;
let's write the code:
#include<bits/stdc++.h>
using namespace std;
int main(){
string s;
cin>>s;
int freq[26] = {0};
for(int i=0;i<s.size();i++){
freq[s[i]-'a']++; // for lowercase string use s[i]-'a';
}
for(int i=0;i<26;i++){
if(freq[i]!=0){
cout<<"freq of "<<char(97+i)<<":"<<freq[i]<<endl;
}
}
}
Above written code is for those string which only have lowercase alphabets.
For better understanding go through the above image:
if we have a string of upper case alphabets. then we have to change our code.
everything will remain same, only make change in both for loop:
In first for loop:
freq[s[i]-'A']++;
In second for loop:
if(freq[i]!=0){
cout<<"freq of "<<char(65+i)<<":"<<freq[i]<<endl;
}
this is the first method.
Method2:
Use hashmap:
#include<bits/stdc++.h>
using namespace std;
int main(){
string s;
cin>>s;
map<char,int>m;
for(int i=0;i<s.size();i++){
if(m.find(s[i])!=m.end()){
auto it = m.find(s[i]);
it->second++;
}
m.insert(make_pair(s[i],1);
}
for(auto it = m.begin(); it != m.end(); it++){
cout<<"freq of "<<it->first<<":"<<it->second<<endl;
}
}
Comments
Post a Comment