How to find the most common pair of characters in a string with C

1 Answer

0 votes
#include <stdio.h>
#include <string.h>

int find_most_common_pair_of_characters(const char* str, char pair[]) {
    int paircount[256][256] = { {0}, {0} };
    
    for (const char* p = str; *(p + 1); p++) {
        paircount[(int)*p][(int)*(p + 1)]++;
    }

    int ia = 0, ib = 0;
    for (int i = 0; i != 256; i++) {
        for (int j = 0; j != 256; j++) {
            if (paircount[i][j] > paircount[ia][ib]) {
                ia = i;
                ib = j;
                pair[0] = i;
                pair[1] = j;
            }
        }
    }

    return paircount[ia][ib];
}

int main()
{
    const char* str = "xzvxdeshaalzxzmdenlopxzxzxzaaqdewrzaaaapeerxzxz";
    char pair[3] = "";

    int times = find_most_common_pair_of_characters(str, pair);
    
    printf("pair: %c%c   times: %d\n", pair[0], pair[1], times);

    return 0;
}



/*
run:

pair: xz   times: 7

*/

 



answered Nov 27, 2024 by avibootz

Related questions

...