
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
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 Occurrences of One String in Another 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