Ortix92 Ortix92 - 1 month ago 15
C++ Question

Check if strings in std::vector contain substring in C++

Is there an efficient way of executing a function if any string inside a vector contains a substring?

Something along these lines

if(vector.contains(strstr(currentVectorElement,"substring"))) {
//do something
}

if(vector.contains(strstr(currentVectorElement,"substring2"))) {
//do something else
}


The only thing I can think of is iterating over each string and check if the substring exists.

Answer

You can use std::find_if with a lambda expression

if(std::find_if(vec.begin(), vec.end(), [](const std::string& str) { return str.find("substring") != std::string::npos; }) != vec.end()) {
    ...
}