在字符串中找出与给定字符串相同的字符串(find a substring from a string)

import sys

def is_substring(actual_str,pattern_str):
if actual_str is None or pattern_str is None:
print 'empty string'
return
if len(pattern_str)>len(actual_str):
print 'substring pattern is longer than catual string'
return
indexes=[]
for i in range(len(actual_str) - len(pattern_str) + 1):
if pattern_str[0]==actual_str[i] and\
pattern_str[len(pattern_str)-1]==actual_str[i+len(pattern_str)-1]:
indexes.append(i)
if len(indexes)==0:
print 'substring could not be found'
return
mismatch=False
for j in range(len(indexes)):
index=indexes[j]
for k in range(len(pattern_str)):
if(actual_str[index]!=pattern_str[k]):
print "Mismatch : %s - %s"%(actual_str[index], pattern_str[k])
mismatch=True
break
index+=1
if mismatch==True:
mismatch=False
continue
print 'substring found at indexes:',indexes[j]

if __name__=='__main__':
if len(sys.argv)!=3:
is_substring('122234542223212527','222')
else:
is_substring(str(sys.argv(1),str(sys.argv[2])))
substring found at indexes: 1
substring found at indexes: 8
Mismatch : 3 - 2
Mismatch : 1 - 2
Mismatch : 5 - 2
>>>



posted @ 2011-12-20 14:48  wyixin  阅读(519)  评论(2编辑  收藏  举报