Check if a string is substring of another

Given two strings s1 and s2, find if s1 is a substring of s2. If yes, return the index of the first occurrence, else return -1.

Examples :

Input: s1 = "for", s2 = "geeksforgeeks"
Output: 5
Explanation:
String "for" is present as a substring
of s2.

Input: s1 = "practice", s2 = "geeksforgeeks"
Output: -1.
Explanation:
There is no occurrence of "practice" in
"geeksforgeeks"

Simple Approach: The idea is to run a loop from start to end and for every index in the given string check whether the sub-string can be formed from that index. This can be done by running a nested loop traversing the given string and in that loop run another loop checking for sub-string from every index.
For example, consider there to be a string of length N and a substring of length M. Then run a nested loop, where the outer loop runs from 0 to (N-M) and the inner loop from 0 to M. For very index check if the sub-string traversed by the inner loop is the given sub-string or not.

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// CPP program to check if a string is
// substring of other.
#include <bits/stdc++.h>
using namespace std;
  
// Returns true if s1 is substring of s2
int isSubstring(string s1, string s2)
{
    int M = s1.length();
    int N = s2.length();
  
    /* A loop to slide pat[] one by one */
    for (int i = 0; i <= N - M; i++) {
        int j;
  
        /* For current index i, check for
 pattern match */
        for (j = 0; j < M; j++)
            if (s2[i + j] != s1[j])
                break;
  
        if (j == M)
            return i;
    }
  
    return -1;
}
  
/* Driver program to test above function */
int main()
{
    string s1 = "for";
    string s2 = "geeksforgeeks";
    int res = isSubstring(s1, s2);
    if (res == -1)
        cout << "Not present";
    else
        cout << "Present at index " << res;
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to check if a string is
// substring of other.
class GFG {
  
    // Returns true if s1 is substring of s2
    static int isSubstring(
        String s1, String s2)
    {
        int M = s1.length();
        int N = s2.length();
  
        /* A loop to slide pat[] one by one */
        for (int i = 0; i <= N - M; i++) {
            int j;
  
            /* For current index i, check for
            pattern match */
            for (j = 0; j < M; j++)
                if (s2.charAt(i + j)
                    != s1.charAt(j))
                    break;
  
            if (j == M)
                return i;
        }
  
        return -1;
    }
  
    /* Driver program to test above function */
    public static void main(String args[])
    {
        String s1 = "for";
        String s2 = "geeksforgeeks";
  
        int res = isSubstring(s1, s2);
  
        if (res == -1)
            System.out.println("Not present");
        else
            System.out.println(
                "Present at index "
                + res);
    }
}
  
// This code is contributed by JaideepPyne.

chevron_right


Python 3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python 3 program to check if 
# a string is substring of other.
  
# Returns true if s1 is substring of s2
def isSubstring(s1, s2):
    M = len(s1)
    N = len(s2)
  
    # A loop to slide pat[] one by one 
    for i in range(N - M + 1):
  
        # For current index i,
        # check for pattern match 
        for j in range(M):
            if (s2[i + j] != s1[j]):
                break
              
        if j + 1 == M :
            return i
  
    return -1
  
# Driver Code
if __name__ == "__main__":
    s1 = "for"
    s2 = "geeksforgeeks"
    res = isSubstring(s1, s2)
    if res == -1 :
        print("Not present")
    else:
        print("Present at index " + str(res))
  
# This code is contributed by ChitraNayal

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to check if a string is
// substring of other.
using System;
class GFG {
  
    // Returns true if s1 is substring of s2
    static int isSubstring(string s1, string s2)
    {
        int M = s1.Length;
        int N = s2.Length;
  
        /* A loop to slide pat[] one by one */
        for (int i = 0; i <= N - M; i++) {
            int j;
  
            /* For current index i, check for
            pattern match */
            for (j = 0; j < M; j++)
                if (s2[i + j] != s1[j])
                    break;
  
            if (j == M)
                return i;
        }
  
        return -1;
    }
  
    /* Driver program to test above function */
    public static void Main()
    {
        string s1 = "for";
        string s2 = "geeksforgeeks";
  
        int res = isSubstring(s1, s2);
  
        if (res == -1)
            Console.Write("Not present");
        else
            Console.Write("Present at index "
                          + res);
    }
}
  
// This code is contributed by nitin mittal.

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// PHP program to check if a 
// string is substring of other.
  
// Returns true if s1 is substring of s2
function isSubstring($s1, $s2)
{
    $M = strlen($s1);
    $N = strlen($s2);
  
    // A loop to slide
    // pat[] one by one 
    for ($i = 0; $i <= $N - $M; $i++) 
    {
        $j = 0;
  
        // For current index i, 
        // check for pattern match
        for (; $j < $M; $j++)
            if ($s2[$i + $j] != $s1[$j])
                break;
  
        if ($j == $M)
            return $i;
    }
  
    return -1;
}
  
// Driver Code
$s1 = "for";
$s2 = "geeksforgeeks";
$res = isSubstring($s1, $s2);
if ($res == -1)
    echo "Not present";
else
    echo "Present at index " . $res;
  
// This code is contributed by mits
?>

chevron_right


Output:

Present at index 5

Complexity Analysis:



  • Time complexity: O(m * n) where m and n are lengths of s1 and s2 respectively.
    A nested loop is used the outer loop runs from 0 to N-M and inner loop from 0 to M so the complexity is O(m*n).
  • Space Complexity: O(1).
    As no extra space is required.

An efficient solution is to use a O(n) searching algorithm like KMP algorithm, Z algorithm, etc.

Language implementations:

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Recommended Posts:


Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.