gpt4 book ai didi

c++ - 在 C++ 中的自定义字符串类中实现插入?

转载 作者:太空宇宙 更新时间:2023-11-04 13:45:48 24 4
gpt4 key购买 nike

我正在用 cpp 实现我自己的 MyString 类。我已经成功完成了 length、isEmpty、find、compare、clear、insert 的功能,并重载了 << 和 == 运算符。我无法完成的唯一功能是插入功能。 insert 的描述是“通过在字符串内容的特定位置 (pos) 插入一些附加内容 (str 或 s) 来扩展当前字符串内容。现有内容向右移动。成功执行函数后返回 0 .否则返回-1。”以下是我现在拥有的功能,它构建和运行没有错误,但逻辑不正确:

// inserts some additional content str at a specific location pos within the string content
int MyString::insert(int pos, const MyString& str) {

if (pos < 0 || pos > size) // out of bounds
return -1;
for (int i = pos; i < pos + str.length(); i++) // shift existing content to right
content[i+str.length()] = content[i];
for (int i = pos; i < pos + str.length(); i++) // insert new content
content[i] = str.content[i-pos];
return 0;

}

content 是我要插入 str 的字符串。我正在使用以下代码对其进行测试:

MyString ms12 = "This string will test the function";
MyString testInsert = "insert ";
ms12.insert(26, testInsert);

一旦插入成功完成,该测试将导致内容为字符串“This string will test the insert function”。当我现在运行代码并打印出 m12 时,我得到的输出是“This string will test the insert functio═════════════════════════ ═══════════════²²²²½½½½½½½½ε■ε■"。所以它是将新数据 str ("insert ") 插入到字符串中,但它没有正确地将之前的内容右移。我用来实现字符串的 char* 数组大小设置为 80,因此我有足够的空间来插入它。

我知道这一定是第一个for循环的逻辑,但我不知道如何修复它。感谢您的帮助。

最佳答案

我认为您应该检查插入内容是否溢出并且内容是否填充为零。此外,您可以稍微简化例程,检查下面的代码片段:

int MyString::insert(size_t pos, const string& str){
if ((pos + str.size()) >= size)
return -1;
memmove(content + pos + str.size(), content + pos , strlen(content));
memcpy(content + pos, str.c_str(), str.size());
return 0;
}

关于c++ - 在 C++ 中的自定义字符串类中实现插入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26070394/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com