Python

Python编程题17--字符串在另一个字符串中的位置

2020-11-14  本文已影响0人  wintests

题目

给定字符串A和字符串B,请检测字符串A是否在字符串B中,如果存在则返回字符串B中每次出现字符串A的起始位置,否则返回 -1 。

例如:

给定一个字符串:GBRRGBRGG,另一个字符串:RG
那么字符串 RG 在 GBRRGBRGG 中出现的位置为 3,6

实现思路1

代码实现

def index_of_str(s1, s2):
    res = []
    len1 = len(s1)
    len2 = len(s2)
    if s1 == "" or s2 == "":
        return -1
    for i in range(len1 - len2 + 1):
        if s1[i] == s2[0] and s1[i:i+len2] == s2:
            res.append(i)
    return res if res else -1

str1 = "cdembccdefacddelhpzmrtcdeqpjcde"
str2 = "cde"
print("字符串 {} 在另一个字符串 {} 中出现的位置:{} ".format(str2, str1, index_of_str(str1, str2)))

实现思路2

注意:split() 分割操作时,如果所指定分割串不在字符串中,那么会返回字符串本身。

代码实现

def index_of_str(s1, s2):
    res = []
    index = 0
    if s1 == "" or s2 == "":
        return -1
    split_list = s1.split(s2)
    for i in range(len(split_list) - 1):
        index += len(split_list[i])
        res.append(index)
        index += len(s2)
    return res if res else -1

str1 = "cdembccdefacddelhpzmrtcdeqpjcde"
str2 = "cde"
print("字符串 {} 在另一个字符串 {} 中出现的位置:{} ".format(str2, str1, index_of_str(str1, str2)))

更多Python编程题,等你来挑战:Python编程题汇总(持续更新中……)

上一篇 下一篇

猜你喜欢

热点阅读