aiaiask.com©

开花即结果 提问即答案

Python中字符串操作:定义、复制、查找与子串提取
原始问题:

Python中字符串操作:定义、复制、查找与子串提取

# 定义串的数据类型
class MyString:
    def __init__(self, length):
        self.data = ['\0'] * length

    def __str__(self):
        return ''.join(self.data)

# 构造长度为50的字符串对象str1
str1 = MyString(50)

# 使用strcpy函数将str1内容赋值为“this is a boy”
strcpy(str1.data, "this is a boy")

# 构造长度为50的字符串对象str2,内容赋值为 “boy”
str2 = MyString(50)
strcpy(str2.data, "boy")

# 使用index函数完成在str1中查找str2子串的位置
index_pos = str1.data.index(str2.data)
print("子串位置:", index_pos)

# 使用substr函数对str1对象求子串,得到的子串字符部分的值为his i
sub_str = str1[index_pos:index_pos + len(str2.data)]
print("子串:", sub_str)
Python中字符串操作:定义、复制、查找与子串提取
https://www.aiaiask.com/ask/59198.html
AI / 模型Siliconflow
时间 / DATENovember 23, 2023, 7:56 PM
语言zh-CN
IP / 区域广东 云浮