C++ 在C++;?
我正在cpp中实现我自己的MyString类。我已经成功地完成了length、isEmpty、find、compare、clear、insert等函数,并重载了我认为您的代码中可能存在一些缺陷C++ 在C++;?,c++,string,insert,C++,String,Insert,我正在cpp中实现我自己的MyString类。我已经成功地完成了length、isEmpty、find、compare、clear、insert等函数,并重载了我认为您的代码中可能存在一些缺陷 第一个if测试可能有缺陷,因为您没有考虑str的长度,这可能是一个大字符串,使大小不够大 移动contnet时,需要用\0标记字符串的结尾 移位算法并不完全正确,正如molbdnilo所指出的,您需要将pos之后的所有字符移位。然后您需要从最后一个字符切换回pos,否则您将覆盖一些字符 我认为您应该检查插
if
测试可能有缺陷,因为您没有考虑str
的长度,这可能是一个大字符串,使大小
不够大contnet
时,需要用\0
标记字符串的结尾pos
之后的所有字符移位。然后您需要从最后一个字符切换回pos
,否则您将覆盖一些字符我认为您应该检查插入内容是否溢出,内容是否为零填充。此外,您还可以稍微简化例程,检查下面的代码段:
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;
}
需要注意两件事:
intmystring::insert(intpos、constmystring&str){
if(pos<0 | | pos>size)//超出范围
返回-1;
int newlen=size+str.length()+1;
char-tmp[newlen];
strcpy(tmp,内容);
for(int i=newlen-1;i>pos;i--)//将现有内容向右移动
tmp[i]=tmp[i-str.length()];//向后复制
for(int i=pos;i
另一个想法是为成员
内容使用std::string
,这将使此方法更加简洁易懂。您需要将整个内容数组移到pos
之外,从“后端”开始移动,然后继续前进,并记住正确的零终止。(我建议从更短的测试字符串开始,这样您就可以轻松地手动跟踪执行。)您需要决定pos
是基于0还是基于1。我说这是第一个测试的原因看起来是错误的:if(pos<0 | | pos>size)//越界
您正在测试字符串左端的0,那么为什么测试size-1
不在字符串右端?1。)谢谢,我没有想到这一点。2.)我标记了字符串的结尾,现在显示为“此字符串将测试插入函数”。所以我的“n”还是不见了。
MyString ms12 = "This string will test the function";
MyString testInsert = "insert ";
ms12.insert(26, testInsert);
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;
}
int MyString::insert(int pos, const MyString& str) {
if (pos < 0 || pos > size) // out of bounds
return -1;
int newlen = size+str.length()+1;
char tmp[newlen];
strcpy(tmp, content);
for (int i = newlen-1; i>pos; i--) // shift existing content to right
tmp[i] = tmp[i-str.length()]; // copy backwards
for (int i = pos; i < pos + str.length(); i++) // insert new content
tmp[i] = str.content[i-pos];
delete content; content = new char[newlen]; // allocate a new array
strcpy(content, tmp);
return 0;
}