How to check whether a user string contains any forbidden words from a list in C++

1 Answer

0 votes
#include <iostream>
#include <unordered_set> // unordered_set
#include <sstream>
#include <string>

bool containsForbidden(const std::string& input,
                       const std::unordered_set<std::string>& forbidden) {
    std::istringstream iss(input);
    std::string word;

    while (iss >> word) {
        if (forbidden.count(word)) {
            return true;
        }
    }
    
    return false;
}

int main() {
    std::unordered_set<std::string> forbidden = {
        "badword", "evil", "kill"
    };

    std::string user = "This is a badword inside the sentence";

    if (containsForbidden(user, forbidden)) {
        std::cout << "Forbidden word detected\n";
    } else {
        std::cout << "No forbidden words found\n";
    }
}



/*
run:

Forbidden word detected

*/

 



answered Dec 26, 2025 by avibootz
edited Dec 26, 2025 by avibootz

Related questions

...