The append and concat functions combine the text of two LPString objects into a single string. The difference between them is how they store and return the combined text. The append function modifies this string, adding the text in the parameter to it. The concat function doesn't change either string; instead, it creates a new LPString object with the combined text of the original strings. Two distinct solutions demonstrate fundamentally different ways of implementing the concat function. The first implementation uses the same basic array notation demonstrated throughout the LPString class. The second, more compact implementation uses other, previously completed member functions. Both implementations follow the steps outlined in Figure 18.
LPString LPString::concat(const LPString& s) const
if (text[0] + s.text[0] >= LENGTH) throw "strings too long to concatenate";This step is the same for both implementations.
Array Version | Member Function Version |
---|---|
LPString local; // (a) for (int i = 0; i <= text[0]; i++) // (b) local.text[i] = text[i]; |
LPString local(*this); // (c) //LPString local = copy(); // (d) |
Array Version | Member Function Version |
---|---|
for (int i = 1; i <= s.text[0]; i++) // (a) local.text[text[0] + i] = s.text[i]; local.text[0] += s.text[0]; // (b) |
local.append(s); // (c) |
text[0]+i
creates an index in local, beginning at its end.return local;
.
Array Version
LPString LPString::concat(const LPString& s) const // fundamental operations solution { if (text[0] + s.text[0] >= LENGTH) // total length may not exceed LENGTH throw "strings too long to concatenate"; LPString local; for (int i = 0; i <= text[0]; i++) // copies this string local.text[i] = text[i]; for (int i = 1; i <= s.text[0]; i++) // appends s to local local.text[text[0] + i] = s.text[i]; local.text[0] += s.text[0]; // updates local's length return local; }
Member Function Version
LPString LPString::concat(const LPString& s) const // Existing functions solution { if (text[0] + s.text[0] >= LENGTH) // total length may not exceed LENGTH throw "strings too long to concatenate"; LPString local(*this); // calls the copy constructor //LPString local = copy(); // alternate for the copy constructor local.append(s); return local; }