 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
#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
Advertisements
 