Is it possible to somehow pass multiple strings to the string::find function?
For example, to find a string I might use this:
str.find("a string");
What I'd like to do is something like this:
str.find("a string" || "another string" || "yet another string")
And have the function return the position of the first occurrence of any of the three strings.
Thanks for any suggestions.
Not with std::string::find
, but you could use std::find_if from <algorithm>
:
std::string str("a string");
std::array<std::string, 3> a{"a string", "another string", "yet another string"};
auto it = std::find_if(begin(a), end(a),
[&](const std::string& s)
{return str.find(s) != std::string::npos; });
if (it != end(a))
{
std::cout << "found";
}
That is not possible but what you can do is:
auto is_there(std::string haystack, std::vector<std::string> needles) -> std::string::size_type {
for(auto needle : needles ){
auto pos = haystack.find(needle);
if(pos != std::string::npos){
return pos;
}
}
return std::string::npos;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With