Find the Number of Substrings of One String Present in Other using C++


In this article, we are given two strings, and we need to find out how many substrings of the 1st string can be found in the 2nd string(the exact substring can occur multiple times). For example

Input : string1 = “fogl”
   string2 = “google”
Output : 6
Explanation : substrings of string1 present in string2 are [ “o”, “g”, “l”, “og”, “gl”,
“ogl” ].

Input : string1 = “ajva”
   string2 = “java”
Output : 5
Explanation : substrings of string1 present in string2 are [ “a”, “j”, “v”, “a”, “va” ].

Approach to find The Solution

Let's discuss how we can solve this problem of finding several substrings present in another string; looking at the examples; we understood that first, we have to see all the substrings of string1 and then we have to check each substring whether it is present in another string or not, If yes then increment the counter and after operating whole string check the result stored in the counter.

C++ Code for the Above Approach

Here is the C++ syntax which we can use as an input to solve the given problem −

Example

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

int main() {
   string str1 = "ajva";
   string str2 = "java";
   int count = 0;// counter to store result
   int n = str1.length();

   for (int i = 0; i < n; i++) {

      string str3; // string3 is initialised to store all substrings of string1
      for (int j = i; j < n; j++) {
         str3 += str1[j];

         // checking whether substring present in another string or not
         if (str2.find(str3) != string::npos)
            count++;
      }
   }
   cout << "Number of substrings of one string present in other : "<< count;
   return 0;
}

Output

Number of substrings of one string present in other : 5

Understanding the code

Firstly, in this code, we are giving value to both the strings and initializing the counter with 0. We are going through the whole string and finding all the substrings possible of str1 and storing them in str3. Then we check each substring of str1, whether present in str2 or not; if yes, then increment the counter by 1 and we are finally printing the output stored in the counter variable.

Conclusion

This article finds the simple solution of finding the number of substrings of one string present in another string. We can write the same program in other languages such as C, java, python, and other languages. We hope you find this article helpful.

Updated on: 25-Nov-2021

248 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements