How do I find all the positions of a substring in a string?

后端 未结 4 1455
臣服心动
臣服心动 2020-12-17 17:07

I want to search a large string for all the locations of a string.

4条回答
  •  伪装坚强ぢ
    2020-12-17 18:05

    I'll add for completeness, there is another approach that is possible with std::search, works like std::string::find, difference is that you work with iterators, something like:

    std::string::iterator it(str.begin()), end(str.end());
    std::string::iterator s_it(search_str.begin()), s_end(search_str.end());
    
    it = std::search(it, end, s_it, s_end);
    
    while(it != end)
    {
      // do something with this position..
    
      // a tiny optimisation could be to buffer the result of the std::distance - heyho..
      it = std::search(std::advance(it, std::distance(s_it, s_end)), end, s_it, s_end);
    }
    

    I find that this sometimes outperforms std::string::find, esp. if you represent your string as a vector.

提交回复
热议问题