2015-10-19 98 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

相关问题