Page 213 - Learn To Program With Scratch
P. 213
First, let’s make a general procedure to insert characters at a specific
position in a string. This procedure, called Insert, takes three parameters:
the input word (strIn), the string (or character) to insert (strAdd), and the
position where you want those new characters (charPos). The procedure
generates a new string (strOut) with strAdd inserted into strIn at the correct
position, as illustrated in the example of Figure 8-7.
Insert
h e l p
help strIn
w strAdd strOut hewlp h e w l p
3 charPos
Figure 8-7: Illustrating the Insert procedure
We’ll add the characters from strIn, one by one, into strOut. When we
reach charPos, we’ll just add the character(s) from strAdd to strOut before
appending the letter at charPos from strIn. The complete procedure is
shown in Figure 8-8.
Figure 8-8: The Insert procedure
First, the procedure initializes strOut to an empty string and sets pos
to 1 to access the first letter of the input string u. It then starts a repeat
loop to append the letters of strIn, one by one, to strOut v. Each iteration
grabs the next letter of strIn and places it in the ch variable w. If the posi-
tion of the current character matches charPos, the procedure appends
strAdd to strOut x. In all cases, ch is appended to strOut y, and pos is incre-
mented to access the next letter of strIn z.
String Processing 191
www.it-ebooks.info

