Solutions to strings HW08:



#-----------------------
a = 'I "ate" the "so-called" "snacks"'
b =  '"' + "can't won't didn't" + '"'
b2 = '''"can't won't didn't"'''    # can't use """ because of the last "
c =  """all's well that
    ends on a new line"""


#-----------------------
def rotateOnce(text):
    return text[1:] + text[0]  # first char to back
# NOTE: this way will give an error if rotating the empty string ""
# Can fix that by changing it to text[1:] + text[:1]

def rotate(text, n):
    for i in range(n):
        text = rotateOnce(text)
    return text

# Alternatively, can automatically move all n to back, but need to handle wrap-around 
def rotate2(text, n):
    #move first n chars to back
    n = n % len(text) # n needs to wrap around if > len(text)
    return text[n:] + text[:n]
    

#-----------------------
def isRotated(A, B):
    #try every rotation
    for curr_rot in range(len(A)):
        if rotate(A, curr_rot) == B:
            return True
    return False

    
#-----------------------
def findWord(text ,word):
    for i in range(len(text)):
        chunk = text[i:i+len(word)]
        #print(chunk)
        if chunk == word:
            return i
    return -1


#-----------------------
def findWordStartingAt(text, word, start):
    for i in range(start, len(text)):
        chunk = text[i:i+len(word)]
        #print(chunk)
        if chunk == word:
            return i
    return -1