Find all the occurrences of a substring in a given string in C++

Given a string s1, find the occurrences of string s2 in s1.

Example 1:

Input: s1 = "superhero"; s2 = "hero"
Output: hero found at 5th position
Explanation: "hero" is substring of "superhero".

Example 2:

Input: s1 = "onlycode"; s2 = "code"
Output: code found at 4th position
Explanation: "code" is a substring of "onlycode".

Code Implementation

//
//  main.cpp
//  Finding Substring
//
//  Created by Himanshu on 19/09/21.
//

#include <iostream>
#include <string>
using namespace std;

void findSubstring (string s1, string s2) {
    long i = 0;
    long pos = 0;
    
    while (pos != -1) {
        pos = s1.find(s2, i);
        i = pos + 1;
        if (pos != -1){
            cout<<s2<<" found at: "<<pos<<endl;
        }
    }
}

int main() {
    string s1 = "onlycode - eat sleep code";
    string s2 = "code";
    
    findSubstring(s1, s2);
    
    return 0;
}

Output

code found at: 4
code found at: 21

Leave a Reply

Your email address will not be published.