This post will discuss how to find all occurrences of a substring in a string in C++.

1. Using string::find

The standard approach to find the index of a substring in a string is with the string::find member function. If the substring doesn’t occur in the string, the function returns string::npos. To find all occurrences of a substring in a string, we can repeatedly call the string::find function within a loop, where the search for the next substring starts with the index of the previous match.

Download  Run Code

Output:

1
3
5

2. Using Boost

Another option is to use the C++ boost library to find all occurrences of the search string in the input. The following solution demonstrates this using the boost::find_all algorithm from the header <boost/algorithm/string/split.hpp>.

Download Code

Output:

1
3
5

That’s all about finding all occurrences of a substring in a string in C++.