Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice Pattern Searching
  • Tutorial on Pattern Searching
  • Naive Pattern Searching
  • Rabin Karp
  • KMP Algorithm
  • Z Algorithm
  • Trie for Pattern Seaching
  • Manacher Algorithm
  • Suffix Tree
  • Ukkonen's Suffix Tree Construction
  • Boyer Moore
  • Aho-Corasick Algorithm
  • Wildcard Pattern Matching
Open In App
Next Article:
Replace two substrings (of a string) with each other
Next article icon

Number of substrings of one string present in other

Last Updated : 07 Oct, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Suppose we are given a string s1, we need to the find total number of substring(including multiple occurrences of the same substring) of s1 which are present in string s2. 

Examples: 

Input : s1 = aab         s2 = aaaab Output :6 Substrings of s1 are ["a", "a", "b", "aa",  "ab", "aab"]. These all are present in s2.  Hence, answer is 6.  Input :s1 = abcd        s2 = swalencud Output :3 

The idea is to consider all substrings of s1 and check if it present in s2.  

Implementation:

C++




// CPP program to count number of substrings of s1
// present in s2.
#include<iostream>
#include<string>
using namespace std;
 
int countSubstrs(string s1, string s2)
{
    int ans = 0;
 
    for (int i = 0; i < s1.length(); i++) {
         
        // s3 stores all substrings of s1
        string s3;
        for (int j = i; j < s1.length(); j++) {
            s3 += s1[j];
 
            // check the presence of s3 in s2
            if (s2.find(s3) != string::npos)
                ans++;
        }
    }
    return ans;
}
 
// Driver code
int main()
{
    string s1 = "aab", s2 = "aaaab";
    cout << countSubstrs(s1, s2);
    return 0;
}
 
 

Java




// Java program to count number of
// substrings of s1 present in s2.
import java.util.*;
 
class GFG
{
 
static int countSubstrs(String s1,
                        String s2)
{
int ans = 0;
 
for (int i = 0; i < s1.length(); i++)
{
     
    // s3 stores all substrings of s1
    String s3 = "";
    char[] s4 = s1.toCharArray();
    for (int j = i; j < s1.length(); j++)
    {
        s3 += s4[j];
 
        // check the presence of s3 in s2
        if (s2.indexOf(s3) != -1)
            ans++;
    }
}
return ans;
}
 
// Driver code
public static void main(String[] args)
{
    String s1 = "aab", s2 = "aaaab";
    System.out.println(countSubstrs(s1, s2));
}
}
 
// This code is contributed by ChitraNayal
 
 

Python 3




# Python 3 program to count number of substrings of s1
# present in s2.
 
# Function for counting no. of substring
# of s1 present in s2
def countSubstrs(s1, s2) :
    ans = 0
    for i in range(len(s1)) :
        s3 = ""
 
        # s3 stores all substrings of s1
        for j in range(i, len(s1)) :
            s3 += s1[j]
 
            # check the presence of s3 in s2
            if s2.find(s3) != -1 :
                ans += 1
    return ans
 
# Driver code
if __name__ == "__main__" :
    s1 = "aab"
    s2 = "aaaab"
 
    # function calling
    print(countSubstrs(s1, s2))
     
# This code is contributed by ANKITRAI1
 
 

C#




// C# program to count number of
// substrings of s1 present in s2.
using System;
 
class GFG
{
static int countSubstrs(String s1,
                        String s2)
{
int ans = 0;
 
for (int i = 0; i < s1.Length; i++)
{
     
    // s3 stores all substrings of s1
    String s3 = "";
    char[] s4 = s1.ToCharArray();
    for (int j = i; j < s1.Length; j++)
    {
        s3 += s4[j];
 
        // check the presence of s3 in s2
        if (s2.IndexOf(s3) != -1)
            ans++;
    }
}
return ans;
}
 
// Driver code
public static void Main(String[] args)
{
    String s1 = "aab", s2 = "aaaab";
    Console.WriteLine(countSubstrs(s1, s2));
}
}
 
// This code is contributed
// by Kirti_Mangal
 
 

PHP




<?php
// PHP program to count number of
// substrings of s1 present in s2.
 
function countSubstrs($s1, $s2)
{
    $ans = 0;
 
    for ($i = 0; $i < strlen($s1); $i++)
    {
         
        // s3 stores all substrings of s1
        $s3 = "";
        for ($j = $i;
             $j < strlen($s1); $j++)
        {
            $s3 += $s1[$j];
 
            // check the presence of s3 in s2
            if (stripos($s2, $s3, 0) != -1)
                $ans++;
        }
    }
    return $ans;
}
 
// Driver code
$s1 = "aab";
$s2 = "aaaab";
echo countSubstrs($s1, $s2);
 
// This code is contributed
// by ChitraNayal
?>
 
 

Javascript




<script>
 
// javascript program to count number of
// substrings of s1 present in s2.
 
function countSubstrs( s1, s2)
{
var ans = 0;
 
for (var i = 0; i < s1.length; i++)
{
     
    // s3 stores all substrings of s1
    var s3 = "";
    var s4 = s1 ;
    for (var j = i; j < s1.length; j++)
    {
        s3 += s4[j];
 
        // check the presence of s3 in s2
        if (s2.indexOf(s3) != -1)
            ans++;
    }
}
return ans;
}
 
// Driver code
 
    var s1 = "aab", s2 = "aaaab";
    document.write(countSubstrs(s1, s2));
 
</script>
 
 
Output
6

Complexity Analysis:

  • Time Complexity: O(n*n*n), as nested loops are used where n is the size of string s1
  • Auxiliary Space: O(n), as extra space for string s3 is being used


Next Article
Replace two substrings (of a string) with each other

S

Shashank_Sharma
Improve
Article Tags :
  • DSA
  • Pattern Searching
  • Strings
  • substring
Practice Tags :
  • Pattern Searching
  • Strings

Similar Reads

  • Number of substrings of a string
    Find total number of non-empty substrings of a string with N characters. Input : str = "abc" Output : 6 Every substring of the given string : "a", "b", "c", "ab", "bc", "abc" Input : str = "abcd" Output : 10 Every substring of the given string : "a", "b", "c", "d", "ab", "bc", "cd", "abc", "bcd" and
    3 min read
  • Sum of all substrings of a string representing a number | Set 1
    Given an integer represented as a string, we need to get the sum of all possible substrings of this string Examples: Input: num = “1234”Output: 1670Explanation: Sum = 1 + 2 + 3 + 4 + 12 + 23 +34 + 123 + 234 + 1234 = 1670 Input: num = “421”Output: 491Explanation: Sum = 4 + 2 + 1 + 42 + 21 + 421 = 491
    11 min read
  • Number of even substrings in a string of digits
    Given a string of digits 0 - 9. The task is to count a number of substrings which when converting into integer form an even number. Examples : Input : str = "1234".Output : 6"2", "4", "12", "34", "234", "1234" are 6 substring which are even.Input : str = "154".Output : 3Input : str = "15".Output : 0
    9 min read
  • Replace two substrings (of a string) with each other
    Given 3 strings S, A and B. The task is to replace every sub-string of S equal to A with B and every sub-string of S equal to B with A. It is possible that two or more sub-strings matching A or B overlap. To avoid confusion about this situation, you should find the leftmost sub-string that matches A
    7 min read
  • Count number of substrings of a string consisting of same characters
    Given a string. The task is to find out the number of substrings consisting of the same characters. Examples: Input: abba Output: 5 The desired substrings are {a}, {b}, {b}, {a}, {bb} Input: bbbcbb Output: 10 Approach: It is known for a string of length n, there are a total of n*(n+1)/2 number of su
    6 min read
  • Count of substrings of a binary string containing K ones
    Given a binary string of length N and an integer K, we need to find out how many substrings of this string are exist which contains exactly K ones. Examples: Input : s = “10010” K = 1 Output : 9 The 9 substrings containing one 1 are, “1”, “10”, “100”, “001”, “01”, “1”, “10”, “0010” and “010”Recommen
    7 min read
  • Count of Reverse Bitonic Substrings in a given String
    Given a string S, the task is to count the number of Reverse Bitonic Substrings in the given string. Reverse bitonic substring: A string in which the ASCII values of the characters of the string follow any of the following patterns: Strictly IncreasingStrictly decreasingDecreasing and then increasin
    8 min read
  • Sum of all substrings of a string representing a number | Set 2 (Constant Extra Space)
    Given a string representing a number, we need to get the sum of all possible sub strings of this string. Examples : Input : s = "6759" Output : 8421 sum = 6 + 7 + 5 + 9 + 67 + 75 + 59 + 675 + 759 + 6759 = 8421 Input : s = "16" Output : 23 sum = 1 + 6 + 16 = 23Recommended PracticeSum of all substring
    7 min read
  • Check if one string is subsequence of other
    Given two strings s1 and s2, find if the first string is a Subsequence of the second string, i.e. if s1 is a subsequence of s2. A subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements. Examples : Input: s1 =
    10 min read
  • Sum of all prefixes of given numeric string
    Given string str having N characters representing an integer, the task is to calculate the sum of all possible prefixes of the given string. Example: Input: str = "1225"Output: 1360Explanation: The prefixes of the given string are 1, 12, 122, and 1225 and their sum will be 1 + 12 + 122 + 1225 = 1360
    8 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences