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 <iostream>
#include <sstream>
#include <vector>

bool matchesPattern(const std::string& pattern, const std::string& sentence) {
    std::stringstream ss(sentence);
    std::vector<std::string> words;
    std::string word;

    // Split sentence into words
    while (ss >> word) {
        words.push_back(word);
    }

    // Length mismatch → automatic failure
    if (pattern.size() != words.size()) {
        return false;
    }

    // Compare each pattern character to the first letter of each word
    for (size_t i = 0; i < pattern.size(); i++) {
        if (tolower(pattern[i]) != tolower(words[i][0])) {
            return false;
        }
    }

    return true;
}

int main() {
    std::string pattern = "jpcrg";
    std::string sentence = "java python c rust go";

    if (matchesPattern(pattern, sentence)) {
        std::cout << "Pattern matches!" << std::endl;
    } else {
        std::cout << "Pattern does NOT match." << std::endl;
    }
}



/*
run:

Pattern matches!

*/

 



answered Jan 6 by avibootz

Related questions

...