自定义一个简单的String类示例(Python风格):
class MyString:
def __init__(self, value=""):
self.value = value
def __str__(self):
return self.value
def __len__(self):
return len(self.value)
def __getitem__(self, index):
return self.value[index]
def __setitem__(self, index, char):
temp_list = list(self.value)
temp_list[index] = char
self.value = ''.join(temp_list)
def __add__(self, other):
return MyString(self.value + str(other))
def __eq__(self, other):
return self.value == str(other)
def __contains__(self, item):
return item in self.value
def upper(self):
return MyString(self.value.upper())
def lower(self):
return MyString(self.value.lower())
# 示例用法
s1 = MyString("Hello")
s2 = MyString("World")
print(s1 + " " + s2) # 输出: Hello World
print(len(s1)) # 输出: 5
print(s1[1]) # 输出: e
s1[0] = "h"
print(s1) # 输出: hello
print(s1.upper()) # 输出: HELLO
print("ello" in s1) # 输出: True
print(s1 == "hello") # 输出: True
这个示例中,定义了一个简单的 MyString
类,包含了常用的字符串操作,比如初始化、字符串拼接、长度获取、索引访问、大小写转换、相等判断等功能。请根据需求进行适当的修改和扩展。