2014-11-05 27 views
1

我將如何找到一個字符串中的子字符串的索引,而不使用find方法和索引方法?我需要循環還是使用len方法?如何找到一個子串的索引?

def substring_test(x,y): 
    if y in x: 
     r = True 
    else: 
     r = False 
    return r 

t = input("Enter a string: ") 
v = input("Enter a starting substring ") 
result = substring_test(sentence, substring) 
print(result) 

回答

0

如果您不能使用findindex方法,那麼你需要暴力破解它。

  1. 開始從位置0

  2. 得到字符,直到字符串的長度是從位置

  3. 搜索如果字符串匹配,返回位置

  4. 否則,增量位置

  5. 如果位置大於或等於differen實際的字符串和搜索字符串返回-1之間CE

  6. 否則轉到2

您可以實現這個算法,像這樣

def substring_test(x, y): 
    if len(y) > len(x): 
     return -1 
    for i in range(len(x) - len(y) + 1): 
     if x[i:i+len(y)] == y: 
      return i 
    return -1 
+0

哦好,感謝解釋它,我從來沒有理解如何現在我可以解釋 – Bob 2014-11-05 03:51:36

+0

@Bob歡迎您:-)如果它可以幫助您,您可以[接受此答案](http://meta.stackexchange.com/a/5235)。 – thefourtheye 2014-11-05 03:54:11

+0

當我穿過它時,不管是什麼 – Bob 2014-11-05 03:56:49

相關問題