Find all occurrences of a substring in a string in C++
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#include <iostream> #include <string> int main() { std::string s = "A,B,C,"; std::string substr = ","; int index = 0; while ((index = s.find(substr, index)) != std::string::npos) { std::cout << index << std::endl; index += substr.length(); } return 0; } |
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>.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
#include <iostream> #include <string> #include <boost/algorithm/string.hpp> int main() { std::string s = "A,B,C,"; std::string substr = ","; std::vector<boost::iterator_range<std::string::const_iterator>> matches; boost::find_all(matches, s, substr); for (auto match : matches) { int index = match.begin() - s.begin(); std::cout << index << std::endl; } return 0; } |
Output:
1
3
5
That’s all about finding all occurrences of a substring in a string in C++.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)