Open In App

Python Program To 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. 




# Python3 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

Output:



Present at index 5

Complexity Analysis: 

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

Another Efficient Solution: 




# Python3 program for the above approach
def Substr(Str, target):
      
    t = 0
    Len = len(Str)
    i = 0
      
    # Iterate from 0 to Len - 1
    for i in range(Len):
        if (t == len(target)):
            break
        if (Str[i] == target[t]):
            t += 1
        else:
            t = 0
              
    if (t < len(target)):
        return -1
    else:
        return (i - t)
  
# Driver code
print(Substr("GeeksForGeeks", "Fr"))
print(Substr("GeeksForGeeks", "For"))
  
# This code is contributed by avanitrachhadiya2155

Output:

18

Complexity Analysis:

The complexity of the above code will be still O(n*m) in the worst case and the space complexity is O(1).

Please refer complete article on Check if a string is substring of another for more details!


Article Tags :