How to find the longest repeating character in a string with C++

1 Answer

0 votes
#include <iostream>
#include <string>

char find_longest_repeating_character(std::string str) {
    int longest_count = 0, size = str.length();
    char longest_repeating_character = ' ';
    
    for (int i = 0; i < size;) {
        char ch = str[i];
        int count = 0;
        for (; i < size && ch == str[i]; i++)
            count++;
        if (count > longest_count) {
            longest_count = count ;
            longest_repeating_character = ch;
        }
    }
    
    return longest_repeating_character;
}

int main() {
    
    std::string str = "aabbbbhhhhhhhdddefgggg88";

    std::cout << find_longest_repeating_character(str);
}





/*
run:

h

*/

 



answered Sep 1, 2023 by avibootz
edited Sep 1, 2023 by avibootz
...