How to check if each letter in a string maps to the first letter of a word in another string with C

1 Answer

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

bool matchesPattern(const char *pattern, const char *sentence) {
    char buffer[256];
    char *words[64];
    int wordCount = 0;

    // Copy sentence into a modifiable buffer
    strncpy(buffer, sentence, sizeof(buffer));
    buffer[sizeof(buffer) - 1] = '\0';

    // Tokenize into words
    char *token = strtok(buffer, " ");
    while (token != NULL) {
        words[wordCount++] = token;
        token = strtok(NULL, " ");
    }

    // Length mismatch
    if ((int)strlen(pattern) != wordCount) {
        return false;
    }

    // Compare pattern letters to first letters of words
    for (int i = 0; i < wordCount; i++) {
        if (tolower(pattern[i]) != tolower(words[i][0])) {
            return false;
        }
    }

    return true;
}

int main(void) {
    const char *pattern = "jpcrg";
    const char *sentence = "java python c rust go";

    if (matchesPattern(pattern, sentence)) {
        printf("Pattern matches!\n");
    } else {
        printf("Pattern does NOT match.\n");
    }

    return 0;
}



/*
run:

Pattern matches!

*/

 



answered Jan 6 by avibootz

Related questions

...