针对常见的字符串操作,完成函数接口定义指示的三个任务:拷贝串、在串s的i位置插入串t,成功返回true,失败返回false、求子串操作 i:str中起始下标 len:substr的长度
时间: 2024-11-27 07:08:11 浏览: 26
在Python中,你可以定义一个名为`StringOperations`的类,包含三个方法来处理常见的字符串操作:
```python
class StringOperations:
def __init__(self, s: str):
self.s = s
# 拷贝字符串
def copy_string(self) -> str:
return self.s.copy()
# 在串s的i位置插入串t
def insert_string_at_index(self, i: int, t: str) -> bool:
if i <= len(self.s) and 0 <= i + len(t) <= len(self.s):
self.s = self.s[:i] + t + self.s[i:]
return True
else:
return False
# 求子串操作 (i, len)
def get_substring(self, i: int, len_: int) -> str:
if i >= 0 and i + len_ <= len(self.s):
return self.s[i:i+len_]
else:
return "Substring not available"
# 示例用法
ops = StringOperations("Hello, World!")
print(ops.copy_string()) # 输出: Hello, World!
print(ops.insert_string_at_index(7, " AI")) # 输出: True, 新字符串: Hello, World! AI
print(ops.get_substring(7, 5)) # 输出: World
```
阅读全文
相关推荐


















