Goal: given strings mainStr and str1, check if str1 is a substring of mainStr. If it is return the index of mainStr where the first substring of str1 starts. Otherwise return -1.
Best python answer:
index = mainStr.find(str1)
Here is one algorithm showing how to find the substring at a fundamental level:
def isSubstring(mainStr, str1): #This method checks if str1 is contained in mainStr. #This method assumes both strings are of length >= 1. #holds -1 to indicate str1 is not contained in mainStr, o.w stores index #of mainStr which corresponds to the start of str1 result = None nMainStr = len(mainStr) nStr1 = len(str1) if nMainStr < nStr1: #nMainStr is too short to contain nStr1 result = -1 else: #look for first char of str1 for ind in range(0,nMainStr): if mainStr[ind] == str1: result = ind break #if the first char of str1 was found if result: #get substring where first char of str1 was found mainSubStr = mainStr[result::] #make sure all str1 is in mainSubStr in order for ind in range(0,nStr1): if str1[ind] != mainSubStr[ind]: # a char in str1 was not found in correct order in mainSubStr # note: if this if clause is not entered, result will contain # index of mainStr corresponding to first char of str1 result = -1 break return result