Pass multiple strings to the string::find function

自闭症网瘾萝莉.ら 提交于 2019-12-23 08:56:39

问题


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.


回答1:


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



回答2:


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



回答3:


Either call find multiple times or construct a regular expression from the strings that you want to find. C++11 has support for regular expressions in <regex>.



来源:https://stackoverflow.com/questions/19952155/pass-multiple-strings-to-the-stringfind-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!