Worked solution from the Programming Paper 2 Problem-solving and Programming booklet, Part 3 of 3.
Go through the string one character at a time. Copy each character to the new string, but swap it for the new character when it matches the original one.
FUNCTION Replace(OldString : STRING, Char1, Char2 : CHAR) RETURNS STRING
DECLARE NewString : STRING
DECLARE ThisChar : CHAR
DECLARE Index : INTEGER
NewString ← ""
FOR Index ← 1 TO LENGTH(OldString)
ThisChar ← MID(OldString, Index, 1)
IF ThisChar = Char1 THEN
ThisChar ← Char2
ENDIF
NewString ← NewString & ThisChar
NEXT Index
RETURN NewString
ENDFUNCTIONFunction heading and ending including the parameters and return type [1]
Local variables declared, including the loop counter [1]
Loop for the length of OldString [1]
Each character extracted and tested against the original character inside the loop [1]
Characters joined with & to build NewString, replacing the character when needed, inside the loop [1]
NewString returned after the loop [1]
▶ Starts at Q4 (28:02)
Starts at Q4 (28:02) · by Pseudocode Pro. Tap the picture to open it on YouTube.
Solutions follow the official Cambridge mark schemes; marks are shown in grey. Videos are from other YouTube channels. Paper codes read component / series / year: M/J = May/June, O/N = October/November. Past-paper questions © UCLES, reproduced for classroom practice.