How to check whether a string is composed only of words from a given list in C++

1 Answer

0 votes
#include <iostream>
#include <sstream>
#include <vector>
#include <unordered_set>

bool containsOnlyWords(const std::string& s, const std::vector<std::string>& allowed) {
    std::unordered_set<std::string> allowedSet(allowed.begin(), allowed.end());

    std::istringstream iss(s);
    std::string word;

    while (iss >> word) {
        if (allowedSet.find(word) == allowedSet.end())
            return false;
    }
    
    return true;
}

int main() {
    std::string s = "aaa bbbb ccccc";
    std::vector<std::string> words = {"aaa", "ccccc", "bbbb", "xxx"};

    std::cout << std::boolalpha << containsOnlyWords(s, words);
}




/*
run:

20 38 24 14 22 46 50 21 42 11 

*/

 



answered Jan 5 by avibootz
...