Quantcast
Viewing all articles
Browse latest Browse all 4

Answer by Pete Becker for Search a string for all occurrences of a substring in C++

The usual approach is to search in place:

std::string::size_type pos = 0;int count = 0;for (;;) {    pos = large.find(small, pos);    if (pos == std::string::npos)        break;++count;++pos;}

That can be tweaked if you're not concerned about overlapping matches (i.e., looking for all occurrences of "ll" in the string "llll", the answer could be 3, which the above algorithm will give, or it could be 2, if you don't allow the next match to overlap the first. To do that, just change ++pos to pos += small.size() to resume the search after the entire preceding match.


Viewing all articles
Browse latest Browse all 4

Trending Articles