Our goal is to experience how pictures can help us see problem details and develop the general algorithms necessary to write program statements. It may not be necessary to draw a detailed picture for each statement, but it can help us solve particularly challenging problems. The following step-by-step solution follows the steps outlined in Figure 19. As you study each figure, focus on the articulation between the picture and the C++ statement. Our overarching goal is not merely writing the function but understanding how to solve the problem with a C++ member function. Ask yourself, "How does the code help solve the overall problem?"
for (int i = text[0] - index; i >= 0; i--)
text[index + s.text[0] + i] = text[index + i];
Step 3: shifting text.
The insert operation may occur anywhere in this string. The function must shift some characters to the right to make room for the inserted text. The shift begins at the insertion point right, index, and proceeds to the end of the string. It's easier to illustrate the shift operation with two arrays, but there is only one array, and the shift operation copies a character from one location in the array to a different location in the same array. Before we can copy a character into an array element, we must "save" the element's contents to an unused location in the array. So, we start the shift operation at the right end of this string, location 12 in this example, and work from right to left - from 12 to 7. Tables are often a good way to track all the operations in a loop, especially in a for-loop where the operations depend on the loop control variable. Notice that i goes from 5 down to 0, which makes the shift operation work from right to left.
i 1 i = text[0] - index
From 2 index + i
Character Shifted text[index + i]
To 3 index + s.text[0] + i
12 - 7 = 5
7 + 5 = 12
!
7 + 4 + 5 = 16
4
7 + 4 = 11
d
7 + 4 + 4 = 15
3
7 + 3 = 10
l
7 + 4 + 3 = 14
2
7 + 2 = 9
r
7 + 4 + 2 = 13
1
7 + 2 = 8
o
7 + 4 + 1 = 12
0
7 + 0 = 7
w
7 + 4 + 0 = 11
The for-loop runs or iterates once for each character it shifts to the right. This value is the number of characters from the index to the end of the string: length - index + 1. The "=" part of the ">=" accounts for the +1.
The index location of the next character the loop shifts right. The assignment operation copies the character from the source location to the destination, leaving the source unchanged (illustrated by the unshaded characters).
The index location where the loop copies the character.