Python 字符串查找: 判断是否存在连续子串 'algorithm'
可以使用简单的遍历方法来判断字符串中是否存在连续子串'algorithm'。以下是一个示例的 Python 代码:
def has_substring(s):
target = 'algorithm'
n = len(s)
m = len(target)
i = 0
while i <= n - m:
j = 0
while j < m and s[i+j] == target[j]:
j += 1
if j == m:
return True
i += 1
return False
# 示例用法
string = 'this is a string containing the word algorithm'
result = has_substring(string)
print(result) # 输出:True
在这个例子中,has_substring函数接收一个字符串s作为参数,通过遍历s的所有可能的起始位置,逐个检查长度为m的子串是否与目标字符串'algorithm'相等。如果找到了相等的子串,则返回True。如果遍历完整个字符串都没有找到相等的子串,则返回False。
请注意,这个方法只判断是否存在连续子串'algorithm',不会输出具体的子串位置。如果需要输出具体的位置,可以在代码中进行相应的修改。
原文地址: https://www.cveoy.top/t/topic/bjZs 著作权归作者所有。请勿转载和采集!