user2848971
user2848971

Reputation:

How to find the first occurrence of any string given a particular group of strings?

For example, I have 3 strings I am interested in finding in a much larger string. How would I use std algorithms to find the first occurrence of anyone of these strings?

std::string str = ...//Some large string to search in.
std::array<std::string, 3> tokens{ "abc", "qwe", "zxc" };

...//Find the the next occurrence of either "abc", "qwe", "zxc" in str, whichever comes first.
...// Process based on the result.

Upvotes: 0

Views: 1890

Answers (1)

Matthieu M.
Matthieu M.

Reputation: 299930

If you are restricted to the Standard Library, or wish for something simple, the simplest alternative would be to search them one at a time and keep the "best" position:

size_t bestIndex = 0;
size_t bestPosition = str.size();

for (size_t i = 0, max = tokens.size(); i < max; ++i) {
    size_t const pos = str.find(tokens[i]);
    if (pos >= bestPosition) { continue; }

    bestPosition = pos;
    bestIndex = i
}

If you have more resources, or wish for more performance, then Aho-Corasick is a good algorithm to search multiple needles in a single pass. It is definitely more complicated though.

Upvotes: 1

Related Questions