I would just like someone to check this function, because I'm not sure if I did it completely right. I have a MyString class with size, capacity, and data member variables. size is like strlen. capacity is size + 1 (for the null terminator) and data is a char array.
In this code, do I need to check for null arrays? I'm not quite sure how to do this.
I'm creating a MyString instance to hold str + this->data and then I return it. I think it's a little sloppy and could maybe be implemented better. Any suggestions? Thanks!
MyString MyString::operator + (const char* str)
{
MyString concatStr;
concatStr.size = this->size + strlen(str);
concatStr.capacity = concatStr.size + 1;
concatStr.data = new char[concatStr.capacity];
// copies the first string
for (int i = 0; i < this->size; i++)
concatStr.data[i] = this->data[i];
// copies the second string
for (int i = 0; i < strlen(str)+1; i++) // plus one for the /0
concatStr.data[i+(this->size)] = str[i];
return concatStr;
}
Question
gflores
I would just like someone to check this function, because I'm not sure if I did it completely right. I have a MyString class with size, capacity, and data member variables. size is like strlen. capacity is size + 1 (for the null terminator) and data is a char array.
In this code, do I need to check for null arrays? I'm not quite sure how to do this.
I'm creating a MyString instance to hold str + this->data and then I return it. I think it's a little sloppy and could maybe be implemented better. Any suggestions? Thanks!
// in testString.cpp
MyString s1;
s1 = s2 + cString; // s2 contains "hi" and cString contains "world"
// s1 should now be... "hiworld"
MyString MyString::operator + (const char* str) { MyString concatStr; concatStr.size = this->size + strlen(str); concatStr.capacity = concatStr.size + 1; concatStr.data = new char[concatStr.capacity]; // copies the first string for (int i = 0; i < this->size; i++) concatStr.data[i] = this->data[i]; // copies the second string for (int i = 0; i < strlen(str)+1; i++) // plus one for the /0 concatStr.data[i+(this->size)] = str[i]; return concatStr; }Link to comment
Share on other sites
6 answers to this question
Recommended Posts