基本要求:
●输入两个字符串,判断两者之间是否存在包含关系(或重复),如果不存在,则打印False 或 0;如果存在,则打印 True 或1,并打印出现重复的索引位置;
例如,输入两个字符串:'It is a good day' 和 'good',则打印True(表示存在包含关系)和索引号8(前个字符串从0 开始数,数到第 8 个开始出现重复)
●不可使用in 或 find 等命令一步到位的给出判断结果!
def str_contain(str1, str2):
len1 = len(str1)
len2 = len(str2)
# 字符串ch1比ch2少
if len1 < len2:
# 计数匹配的个数
count = 0
i = 0
while i < len1:
j = 0
# 遍历str2中的每个字符
while j < len2:
if list(str1)[i] == list(str2)[j]:
print("True,相同字符在str1中的位置{},相同字符在str2中的位置{}.".format(i,j))
count += 1
break
j += 1
i += 1
if count == 0:
print("false")
else:
# 字符串ch1比ch2多
# 计数匹配的个数
count = 0
i = 0
while i < len2:
j = 0
# 遍历str1中的每个字符
while j < len1:
if list(str1)[j] == list(str2)[i]:
print("True,相同字符在str1中的位置{},相同字符在str2中的位置{}.".format(j,i ))
count += 1
break
j += 1
i += 1
if count == 0:
print("false")
return True
if __name__ == "__main__":
str1 = input("请输入第一串字符:")
str2 = input("请输入第二串字符:")
# print(str1,str2)
str_contain(str1, str2)
print(str1 + "与" + str2)
课程上机任务小练习
如有不足 多多指教