Find indices of all occurrence of one string in other in C++


Suppose we have string str, and another substring sub_str, we have to find the indices for all occurrences of the sub_str in str. Suppose the str is “aabbababaabbbabbaaabba”, and sub_str is “abb”, then the indices will be 1 9 13 18.

To solve this problem, we can use the substr() function in C++ STL. This function takes the initial position from where it will start checking, and the length of the substring, if that is the same as the sub_str, then returns the position.

Example

 Live Demo

#include<iostream>
using namespace std;
void substrPosition(string str, string sub_str) {
   bool flag = false;
   for (int i = 0; i < str.length(); i++) {
      if (str.substr(i, sub_str.length()) == sub_str) {
         cout << i << " ";
         flag = true;
      }
   }
   if (flag == false)
      cout << "NONE";
}
int main() {
   string str = "aabbababaabbbabbaaabba";
   string sub_str = "abb";
   cout << "Substrings are present at: ";
   substrPosition(str, sub_str);
}

Output

Substrings are present at: 1 9 13 18

Updated on: 19-Dec-2019

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements