0

I have a substring defined by two iterators (start and end). I need to check if this substring is present in another string.

Is there a standard library algorithm or string member I can use or adapt to do this without creating a whole new string object (std::string(start, end)) just for this purpose?

e.g.

struct Substring
{
    std::string::const_iterator start, end;
};

auto found = std::contains(whole.begin(), whole.end(), substring.start, substring.end); // ???
2
  • Boost has boost::algorithm::contains boost.org/doc/libs/1_55_0/doc/html/string_algo/… Commented Sep 30, 2015 at 12:50
  • 1
    FWIW, there's soon going to be a couple of new search methods like Boyer-Moore if you need something of that calibre. I know libstdc++ has implemented these already. Commented Sep 30, 2015 at 12:54

2 Answers 2

11

std::search

bool found = 
    std::search(hay.begin(), hay.end(), needle.begin(), needle.end()) != hay.end();
Sign up to request clarification or add additional context in comments.

1 Comment

Haha. I'm not quite sure how I forgot / missed std::search. Thanks.
0

You can use the std::string::find method:

auto found = (whole.find(&*substring.start, 0, substring.end - substring.start)
              != std::string::npos);

The advantage over std::search is that std::find works on strings and can be implemented using Boyer-Moore. Sadly, that is not how gcc's libstdc++ implements it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.