Just write your own loop to copy chars without the null-terminator?
However, on this line:
m_length = <strong>strlen</strong>(m_buffer) + <strong>strlen</strong>(other) + 1;
You are using a function which relies on the null-terminator at the end of the string, so you will have to keep track of the string length yourself while adding characters to it. Something like this perhaps?
String& String::operator +=(char* other) {
// Temporarily store the old length (for copying chars)
size_t oldLength = m_length;
// New size of string
m_length += strlen(other);
// Allocate enough space for the new string
char *new_str = new char[m_length];
// Copy string without null-terminator
for (size_t i = 0; i < oldLength; ++i)
new_str[i] = m_buffer[i];
// Delete old chars
delete[] m_buffer;
// Assign new string
m_buffer = new_str;
return *this;
}
Hope this helps.
William Hemsworth
Posting Virtuoso
1,591 posts since Mar 2008
Reputation Points: 1,429
Solved Threads: 129
Sorry, my mistake :P
String& String::operator +=(char* other) {
// Temporarily store the old length (for copying chars)
size_t oldLength = m_length;
// New size of string
m_length += strlen(other);
// Allocate enough space for the new string
char *new_str = new char[m_length];
// Copy string without null-terminator
for (size_t i = 0; i < oldLength; ++i)
new_str[i] = m_buffer[i];
for (size_t i = oldLength, j = 0; i < m_length; ++i, ++j)
new_str[i] = other[i];
// Delete old chars
delete[] m_buffer;
// Assign new string
m_buffer = new_str;
return *this;
}
Haven't really tried compiling this, but I think it's right this time.
William Hemsworth
Posting Virtuoso
1,591 posts since Mar 2008
Reputation Points: 1,429
Solved Threads: 129
William Hensworth's code declares memory for the new string and copies the char from the original string into the new string, but it doesn't copy the char from other into the new string. You will need to add another loop to do that, but it's only a slightly different version of lines 12 and 13, so I'm sure you can figure it out. When you're done copying other into new_str, then you need reassign new_str to m_buffer as William Hemsworth did.
Edit: I need to remember to recheck each time before I post. Sorry.
Lerner
Nearly a Posting Maven
2,382 posts since Jul 2005
Reputation Points: 739
Solved Threads: 396
In case anybody else tries it.
for (size_t i = oldLength, j = 0; i < m_length; ++i, ++j)
new_str[i] = other[<strong>j</strong>];
I don't know what's wrong with me today, two mistakes in one thread :icon_redface:
William Hemsworth
Posting Virtuoso
1,591 posts since Mar 2008
Reputation Points: 1,429
Solved Threads: 129