How to group words by first letter in C

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h> // realloc
#include <ctype.h> // toupper

// Structure representing a group of words that share the same first letter
typedef struct {
    char letter;        // The first letter (key)
    char **words;       // Dynamic array of strings
    int count;          // Number of words in the group
} WordGroup;


// Function that groups words by their first letter
// Returns the number of groups created
int groupByFirstLetter(char *words[], int wordCount, WordGroup **outGroups) {
    WordGroup *groups = NULL;
    int groupCount = 0;

    for (int i = 0; i < wordCount; i++) {
        char first = words[i][0];

        // Convert to uppercase for consistent grouping
        first = toupper(first);

        // Check if a group for this letter already exists
        int found = -1;
        for (int g = 0; g < groupCount; g++) {
            if (groups[g].letter == first) {
                found = g;
                break;
            }
        }

        // If no group exists, create a new one
        if (found == -1) {
            groups = realloc(groups, sizeof(WordGroup) * (groupCount + 1));
            groups[groupCount].letter = first;
            groups[groupCount].words = NULL;
            groups[groupCount].count = 0;
            found = groupCount;
            groupCount++;
        }

        // Add the word to the group
        WordGroup *grp = &groups[found];
        grp->words = realloc(grp->words, sizeof(char*) * (grp->count + 1));
        grp->words[grp->count] = words[i];
        grp->count++;
    }

    *outGroups = groups;
    
    return groupCount;
}


int main() {
    // List of words to group
    char *words[] = {
        "Python", "JavaScript", "C", "Java", "C#", "PHP",
        "C++", "Pascal", "SQL", "Rust"
    };
    int wordCount = sizeof(words) / sizeof(words[0]);

    WordGroup *groups = NULL;
    int groupCount = groupByFirstLetter(words, wordCount, &groups);

    // Print each group 
    for (int i = 0; i < groupCount; i++) {
        printf("%c: [", groups[i].letter);
        for (int j = 0; j < groups[i].count; j++) {
            printf("%s", groups[i].words[j]);
            if (j < groups[i].count - 1) printf(", ");
        }
        printf("]\n");
    }

    // Free allocated memory
    for (int i = 0; i < groupCount; i++) {
        free(groups[i].words);
    }
    free(groups);

    return 0;
}


/*
run:

P: [Python, PHP, Pascal]
J: [JavaScript, Java]
C: [C, C#, C++]
S: [SQL]
R: [Rust]

*/

 



answered Jan 17 by avibootz
...