避免使用递归函数来找到子字符串的解决方法可以使用循环和字符串操作来实现。以下是一个示例代码:
def find_substring(string, substring):
start = 0
while start < len(string):
index = string.find(substring, start)
if index == -1:
break
print("Substring found at index:", index)
start = index + 1
# 示例用法
string = "Hello, World! This is a test string."
substring = "is"
find_substring(string, substring)
在上面的示例中,我们使用了str.find()
函数来查找子字符串在给定字符串中的索引位置。find()
函数返回子字符串的第一个匹配项的索引,如果没有找到则返回-1。我们通过循环和递增的起始索引来查找所有的子字符串匹配项。