• Courses
  • Tutorials
  • DSA
  • Data Science
  • Web Tech
July 18, 2024 |44.7K Views

Check if a string is a substring of another

  Share   Like
Description
Discussion

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.

 

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.

Check if a string is a substring of another: https://www.geeksforgeeks.org/check-string-substring-another/