How to find the second most frequent character in a string with C++

1 Answer

0 votes
#include <iostream>
   
char GetSecondMostFrequentChar(std::string s) { 
    int count[256] = {0}; // 256 = ASCII table size
         
    for (int i = 0; i < s.size(); i++) {
        count[s[i]]++; 
    }
 
    int first = 0, second = 0;
     
    for (int i = 0; i < 256; i++) {
        if (count[i] > count[first]) {
            second = first;
            first = i;
        } else if (count[i] > count[second] && count[i] != count[first]) {
                   second = i;
                }
    }
         
    return char(second);
 } 
   
int main() {
    std::string str = "bbaddddccce";
   
    std::cout << GetSecondMostFrequentChar(str);
      
    return 0;
}
   
   
   
   
/*
run:
   
c
   
*/

 



answered Aug 31, 2022 by avibootz
edited Aug 31, 2022 by avibootz

Related questions

1 answer 113 views
1 answer 131 views
2 answers 159 views
1 answer 113 views
1 answer 143 views
...