替换字符串中所有子串 【问题描述】 输入三个字符串,将主串s1中所有与字符串s2相同的子串替换成字符串s3。 【输入形式】 第一行输入主串s1,第二行输入待替换的子串s2,第三行输入替换字串s3。 【输出形式】 输出替换字串后的主创。 【样例输入】 A beautiful sunrise started the day, with black clouds slowly lit by the bright yellow sun. sun moon 【样例输出】 A beautiful moonrise started the day, with black clouds slowly lit by the bright yellow moon. 【评分标准】 填充各个函数,利用已有函数完成子串替换。
时间: 2023-06-08 11:07:40 浏览: 57
以下是代码实现:
```python
def replace_all(s1: str, s2: str, s3: str) -> str:
l_s1 = len(s1)
l_s2 = len(s2)
ans = ""
i = 0
while i < l_s1:
if s1[i:i+l_s2] == s2:
ans += s3
i += l_s2
else:
ans += s1[i]
i += 1
return ans
s1 = input().strip()
s2 = input().strip()
s3 = input().strip()
print(replace_all(s1, s2, s3))
```
如有需要,可以将函数改为类的形式。注意,本程序只替换主串中与子串相同的子串,如果子串与主串中其他子串有包含关系,也会被替换,例如上例中的 "sun" 和 "sunrise",需要自行避免这种问题。
相关问题
输入2个字符串s1和s2,要求删除s1中出现的所有子串s2,即结果字符串中不能包括s2
以下是Python代码实现:
```python
def remove_substring(s1, s2):
result = ""
i = 0
while i < len(s1):
if s1[i:i+len(s2)] == s2:
i += len(s2)
else:
result += s1[i]
i += 1
return result
```
函数`remove_substring`接受两个字符串`s1`和`s2`,并返回一个新的字符串,其中`s1`中出现的所有子串`s2`都被删除了。
函数的实现是通过遍历`s1`的每个字符,如果当前字符及其之后的字符与`s2`相同,则跳过`s2`长度的字符,否则将当前字符添加到结果字符串中。
例如,如果`s1="hello world"`,`s2="l"`,则函数将返回`heo word`。
输入2个字符串S1和S2,要求删除字符串S1中出现的所有子串S2,即结果字符串中不能包含S2。
可以使用字符串替换的方法来实现删除字符串S1中所有出现的子串S2。具体步骤如下:
1. 使用字符串的 replace() 方法,将S1中所有的S2替换为空字符串 ""。
2. 返回替换后的S1字符串。
以下是 Python 代码实现:
```python
def delete_substring(s1, s2):
return s1.replace(s2, "")
```
示例:
```python
s1 = "hello world, world is beautiful"
s2 = "world"
result = delete_substring(s1, s2)
print(result) # 输出:hello , is beautiful
```
注意:该方法只能删除S1中出现的所有S2子串,无法处理S1中某些子串被S2包含的情况。例如,若S1="hello worl",S2="world",则该方法无法处理。