Performs a search-and-replace on a line of text. The program asks for a message, then for the string to be changed and the new string to put in its place, and rewrites the message with every occurrence replaced. After the replacements are made, pressing R asks for another pair of strings to apply to the edited message, and any other key clears the screen and starts over.
Program Analysis
Program Structure
The whole program is about twenty lines. Lines 100–180 collect the message A$, the target B$ and the replacement C$, echoing each on screen. Lines 200–220 scan A$ one position at a time, comparing the slice A$(N TO N+LEN B$-1) with B$. On a match, line 300 rebuilds the message from three slices (the text before the match, C$, and the text after it), reprints it and returns to the NEXT N at line 220 to keep scanning.
Potential Issues
- The scan runs
FOR N=1 TO LEN A$-LEN B$, one short of the last possible starting position, so a match at the very end of the message is never found. - The loop limit is calculated once, when the
FORstarts. If the replacement is shorter than the target, the message shrinks while the loop keeps running to the old limit, and the slice at line 210 can run past the end of the string and stop with a subscript error. - Scanning resumes right after the start of the replaced text rather than after its end, so a replacement that itself contains the target string can be matched again.
Source Code
100 PRINT AT 21,0;"INPUT MESSAGE?"
110 INPUT A$
120 PRINT AT 0,0;A$
130 PRINT AT 21,0;"INPUT STRING TO BE CHANGED?"
140 INPUT B$
150 PRINT AT 19,0;B$
160 PRINT AT 21,0;"INPUT NEW STRING? "
170 INPUT C$
175 PRINT AT 21,0;" "
180 PRINT AT 20,0;C$
200 FOR N=1 TO LEN A$-LEN B$
210 IF A$(N TO N+LEN B$-1)=B$ THEN GOTO 300
220 NEXT N
230 PAUSE 40000
240 IF INKEY$ ="R" THEN GOTO 130
250 CLS
260 RUN
300 LET A$=A$( TO N-1)+C$+A$(N+LEN B$ TO LEN A$)
310 CLS
320 PRINT AT 0,0;A$
330 GOTO 220
9998 SAVE "RESPEL[L]"
9999 RUNNote: Type-in program listings on this website use ZMAKEBAS notation for graphics characters.
