Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass multiple strings to the string::find function

Tags:

c++

string

find

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.

like image 557
navig8tr Avatar asked Nov 13 '13 11:11

navig8tr


2 Answers

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";
}
like image 75
Jesse Good Avatar answered Oct 21 '22 19:10

Jesse Good


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;
}  
like image 37
RedX Avatar answered Oct 21 '22 20:10

RedX