Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

40,003 questions

51,950 answers

573 users

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

...