2015-10-19 59 views
-1

我想寫一些在字符串中查找子字符串的代碼。到目前爲止,我有這樣的:在Python中查找沒有內置函數的字符串的子字符串

main = "dedicated" 
sub = "cat" 
count = 0 
for i in range (0,len(main)): 
    match = True 
    if sub[0]==main[i]: 
    j=0 
    for j in range(0,len(sub)): 
     if sub[j]!=main[i+j]: 
      match = False 
      print "No substring" 
      break 
     else: 
      count=count+1 
      if match == True and count == len(sub): 
       print "Substring" 
       print "Position start:",i 
  • 「奉獻」和「貓」的作品
  • 「這是一個例子」和「榜樣」返回IndexError
  • 「一無所有」和「不同」的回報沒有任何東西

任何人都可以幫助我/給我指針/改進代碼,使其工作正確與上面的項目符號點?

+0

你有問題嗎? – jonrsharpe

+0

您可以提供有關IndexError的更多詳細信息嗎? –

+0

它返回「IndexError:字符串索引超出範圍」 – Sectah

回答

0
def index(s, sub): 
    start = 0 
    end = 0 
    while start < len(s): 
     if s[start+end] != sub[end]: 
      start += 1 
      end = 0 
      continue 
     end += 1 
     if end == len(sub): 
      return start 
    return -1 

輸出:

>>> index("dedicate", 'cat') 
4 
>>> index("this is an example", 'example') 
11 
>>> index('hello world', 'word') 
-1 
0

爲了解決您的問題,補充一點:在最後

main = "this is an example" 
sub = "example" 
count = 0 
done = False 
for i in range (0,len(main)): 
    match = True 
    if sub[0]==main[i]: 
    j=0 
    for j in range(0,len(sub)): 
     if sub[j]!=main[i+j]: 
      match = False 
      print "No substring" 
      break 
     else: 
      count=count+1 
      if match == True and count == len(sub): 
       print "Substring" 
       print "Position start:",i 
       done = True 
       break 
    if done == True: 
    break 

通知,你就大功告成了..所以然後將它與一個變量來結束程序,並打破循環。然後突破外部循環。

然而你需要解決的問題,潛艇可能會嘗試並超過主要的長度,例如。

main = "this is an example" 
sub = "examples" 

在這種情況下,您需要檢查j迭代器是否超出範圍。我會把它留給你弄清楚,因爲它不是原始問題的一部分。

+0

嘿,感謝您的幫助。然而,在嘗試了幾個不同的輸入之後,我發現「已去除」和「貓」返回: '無子串 子串 位置開始:6'。 – Sectah

相關問題