Search code examples
c++

std::string.find ("string1" || "string2") with or statements between arguments, is it possible?


This code compiles and runs, but it does not find anything:

#include <string>

std::string str = "Arms-3"

if (str.find("Legs" || "Arms" || "Head" || "Body") != std::string::npos) {
    ...
}

Am I missing something obvious, or is there an equivalent function that could do the same without a loop?


Solution

  • If you really insist on doing this without a (visible) loop, one possibility would be to use a regex:

    #include <string>
    #include <regex>
    #include <iostream>
    
    int main() { 
        std::string str("Arms-3");
    
        if (std::regex_search(str, std::regex("Legs|Arms|Head|Body"))) {
            std::cout << "found\n";
        }
    }
    

    Whether this is a good idea or not will depend on why you want to avoid using a loop. If your concern is primarily to keep what seems like a simple operation, looking simple and readable, this may work great. If you're concerned about maximum efficiency, an explicit loop may be a better bet.