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.

WrongThis is accepted as an assignment, then fails: there is no print, and a string has no [0].
name = "Cambridge"
print(name[0])
Right
DECLARE Word : STRING
Word <- "Cambridge"
OUTPUT SUBSTRING(Word, 1, 1)
Output
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.

Right
DECLARE Word : STRING
Word <- "Cambridge"
OUTPUT SUBSTRING(Word, 1, 3)
Output
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), then SUBSTRING(Word, i, 1).
  • Join with &: Initial & ". " & Surname. The + sign is for numbers.

Initials are two one-character slices

Right
DECLARE First : STRING
DECLARE Surname : STRING
First <- "Ada"
Surname <- "Lovelace"
OUTPUT SUBSTRING(First, 1, 1) & SUBSTRING(Surname, 1, 1)
Output
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