将多个字符串传递给string :: find函数

时间:2013-11-13 11:09:58

标签: c++ string find

是否有可能以某种方式将多个字符串传递给string :: find函数?

例如,要查找字符串,我可以使用它:

str.find("a string");

我想做的是这样的事情:

str.find("a string" || "another string" || "yet another string")

让函数返回三个字符串中任何一个字符串的第一次出现的位置。

感谢您的任何建议。

3 个答案:

答案 0 :(得分:14)

不在std::string::find,但您可以使用<algorithm>中的std::find_if

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";
}

答案 1 :(得分:2)

这是不可能的,但你可以做的是:

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;
}  

答案 2 :(得分:1)

多次调用find或从您要查找的字符串构造正则表达式。 C ++ 11支持<regex>中的正则表达式。