Paper 2 · Strings
The first character of a string is position 1
· 5 min read · For students
String questions on Paper 2 are small and precise: take the first letter, take three characters, join a surname onto an initial. The functions are LENGTH and SUBSTRING, the join is &, and the first character is at position 1.
name = "Cambridge"
print(name[0])DECLARE Word : STRING
Word <- "Cambridge"
OUTPUT SUBSTRING(Word, 1, 1)C
SUBSTRING(string, start, length)
The third value is how many characters to take, not the position to stop at. SUBSTRING(Word, 1, 3) is characters 1, 2 and 3. It is not “from 1 to 3” in the Python sense, where the end index is left out.
DECLARE Word : STRING
Word <- "Cambridge"
OUTPUT SUBSTRING(Word, 1, 3)Cam
LENGTH(Word)is the number of characters. For"Cambridge"that is 10.- The last character is
SUBSTRING(Word, LENGTH(Word), 1). - A loop over every character is
FOR i <- 1 TO LENGTH(Word), thenSUBSTRING(Word, i, 1). - Join with
&:Initial & ". " & Surname. The+sign is for numbers.
Initials are two one-character slices
DECLARE First : STRING
DECLARE Surname : STRING
First <- "Ada"
Surname <- "Lovelace"
OUTPUT SUBSTRING(First, 1, 1) & SUBSTRING(Surname, 1, 1)AL
That is the whole of a lot of 2-mark and 3-mark string items. The LENGTH lesson, the SUBSTRING lesson and the initials lesson do each piece, and the reference is string functions.
Check your own code
Run it in the compiler. A mistake is explained in plain English, and many of them have a one-click fix.
More from the blog
- How to fill a trace table the way the mark scheme doesFor students
- Cambridge arrays start at 1For students
- The validation checks Paper 2 actually asks forFor students