Search code examples
pythonalgorithmstring-matching

Can't print the stringMatching pattern


When i run this code I didn't get any error, but I can't print out my code on below.

I've tried to change condition places change but didn't work. Where is my mistake and how to fix it?

def stringMatching(text, pattern):
  for i in range (len(text) - len(pattern)):
  j = 0
  while j < len(pattern) & pattern[j] == text[i+j]:
    j = j + 1
  if j == len(pattern):
    return -1
string = "Chapter I. The quick brown fox jumped over the lazy dog."
substr = "over the"
print(stringMatching([string],[substr])) 

Solution

  • Assuming you're looking for substrings, you can just use the find() method like below:

    print(string.find(substr))
    

    if the result is > -1, it is a substring. You can also make a function if you want just a return 0/ -1 like so:

    string = "Chapter I. The quick brown fox jumped over the lazy dog."
    substr = "over the"
    substr2 = "lazy hat"
    
    def checkSubstring(string, substring):
        if string.find(substring) > -1:
            print("Within the Text")
            return 0
        else:
            print("Not within the Text")
            return -1
    
    checkSubstring(string, substr)
    checkSubstring(string, substr2)
    

    which returns 0 and -1 respectively