Open In App

Java Program To Check If A String Is Substring Of Another

Last Updated : 13 May, 2024
Comments
Improve
Suggest changes
1 Like
Like
Report

Write a java program for a 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"

Naive Approach:

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 running another loop checking for sub-strings starting from every index.

Follow the steps below to implement the idea:

  • Run a for loop with counter i from 0 to N – M.
    • Run a for loop with counter j from 0 to M-1.
      • Compare jth character of S1 with (i+j)th character of S2.
      • If the loop terminates after matching all the characters, then return i, i.e. substring S1 is found starting from ith character of S2
  • Return -1 as no substring is found.

Below is the Implementation of the above idea.


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.

Java Program To Check If A String Is Substring Of Another using Java Library:

The indexOf method in Java is used for finding the starting index of a substring in a given string.

Below is the Implementation of above approach.


Output
Present at index 5

Time Complexity: O(N) , where N is the length of the longer string s2
Auxiliary space: O(1)

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



Next Article

Similar Reads