匹配: 检查一个字符串是否包含另外一个字符串
程序员文章站
2023-12-21 15:49:40
...
源码: simple.py
# -.- coding:utf-8 -.-
#
# 检查一个字符是否包含另外一个字符.
#
# 相似功能, in 关键字, 举例:
# if "a" in "abc":
# return True
# else:
# return False
from __future__ import print_function
def in_(letters, find):
"""
:return: True or False
"""
# 字符集的总长度
letters_len = len(letters)
# 匹配关键字的总长度
find_len = len(find)
# 利用分片, 从
# 0: 0+find_len
# 1: 1+find_len
# 2: 2+find_len
# ...
# 以此类推去查找.
for i in range(letters_len):
print(i)
if letters[i:i+find_len] == find:
return True
# 未命中则返回False
return False
if __name__ == '__main__':
print(in_("abcdefg", "fg"))
# 一共查找了7次
# output
0
1
2
3
4
5
6
False
源码: optimize.py
# -.- coding:utf-8 -.-
#
# 检查一个字符是否包含另外一个字符.
#
# 相似功能, in 关键字, 举例:
# if "a" in "abc":
# return True
# else:
# return False
from __future__ import print_function
def in_(letters, find):
letters_len = len(letters)
find_len = len(find)
max_index = letters_len - find_len
for i in range(max_index + 1):
print(i)
if letters[i:i+find_len] == find:
return True
return False
if __name__ == '__main__':
print(in_("abcdefg", "fg"))
# 一共查找了6次
# output
0
1
2
3
4
5
True
源码: final.py
# -.- coding:utf-8 -.-
# 检查一个字符是否包含另外一个字符.
from __future__ import print_function
# 不采用分片的写法.
def has_substring(search, find):
if not search:
return bool(find)
max_search_index = len(search) - len(find)
for i in range(0, max_search_index+1):
found = True
for j in range(0, len(find)):
if search[i+j] != find[j]:
found = False
break
if found:
return found
return False
if __name__ == '__main__':
print(has_substring("abcdefg", "gh"))