Check if a string is substring of another

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

Examples :

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

Input : s1 = "practice", s2 = "geeksforgeeks"
Output : -1.

A simple solution is to one by one check every index of s2. For every index, check if s1 is present.

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

Time complexity : O(m * n) where m and n are lengths of s1 and s2 respectively.

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

Language implementations :



My Personal Notes arrow_drop_up

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.