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.
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)
concat steps 2 and 3: create and initialize local. The program creates an LPString object named local in the concat function's scope and copies the characters saved in this to it.
An automatic or local variable definition.
The for-loop copies this to local. Starting the loop at 0 copies the length and the text.
The copy constructor creates local, dereferences this, and copies the contents of the dereferenced string to the local variable.
An alternate to (c): defines local as in (a) but uses the copy function, written in the previous section, to copy this to it.
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)
concat steps 4 and 5: append s to local and update its length. The function finishes the concatenation operation by appending s to the end of local.
The for-loop starts at 1 and iterates once for each character in s. text[0]+i creates an index in local, beginning at its end.
Sums the lengths of the two strings and saves the sum as the new length of local.
We previously created the append function and use it here to append s to the end of local.
Both version finish by returning local: return local;.