CIE IGCSE | 8.1.4E.1 String Length and Substrings

Lesson objective

Use LENGTH to count string characters and SUBSTRING to extract a specified number from a starting position, checking bounds and preserving the original data.

Learn

8.1.4E.1 | STRING LENGTH AND SUBSTRINGS

01 | TEXT HAS AN ORDER AS WELL AS A MEANING

A student code such as AB0072 is text, but it also has a structure: the first two characters identify a group, and the last four identify a student within that group. A program may need to inspect those parts separately.

A string is an ordered sequence of zero or more characters. A character can be a letter, digit, punctuation symbol or space.

String length is the number of characters in the string. A substring is a consecutive part extracted from it, such as AB or 0072.

The operations in this lesson are Cambridge pseudocode LENGTH and SUBSTRING. We use a first position of one, following the syllabus convention, rather than importing another language’s indexing rules.

02 | LENGTH COUNTS CHARACTERS

LENGTH returns an INTEGER giving the number of characters in a string. “Returns” means the operation produces a value that an instruction can use.

DECLARE StudentCode : STRING
DECLARE TextLength : INTEGER
StudentCode ← "AB0072"
TextLength ← LENGTH(StudentCode)
OUTPUT TextLength

TextLength receives six, so the output is six. LENGTH does not remove characters or change StudentCode; it calculates a result from the current string.

The parentheses contain the string being examined. This input to an operation is called an argument. Here, StudentCode supplies the argument.

LENGTH counts characters, not the number of words or the numerical value of a digit sequence. LENGTH of the string "0072" is four, not seventy-two.

03 | SPACES COUNT, DELIMITING QUOTES DO NOT

A space is a character, even though it looks blank. The space between Happy and Days makes "Happy Days" ten characters long.

Double quotes mark literal boundaries; they are not part of these stored values
String value in pseudocodeLengthReason
"Happy Days"10Five letters, one space, four letters
"AB0072"6Two letters and four digits
"A B"3Letter, space, letter
" "1One space
""0No characters

The empty string "" and the one-space string " " are different values. An empty string has no characters; a space-only string contains a character.

If the stored text itself includes quote characters, those stored characters count too. Here, we are discussing the surrounding quotes used to write a literal in pseudocode.

Do not infer storage bytes from LENGTH. Character count and encoded file size are different quantities.

04 | NUMBER THE

1H
2a
3p
4p
5y
6SPACE
7D
8a
9y
10s
FROM ONE

A position identifies where a character occurs in the sequence. For Cambridge SUBSTRING examples, the first character is at position one.

1H
2a
3p
4p
5y
6SPACE
7D
8a
9y
10s

Position six is a space. The label SPACE in the illustration makes that blank visible; it represents one stored character, not the five letters of the label.

Positions run from one to LENGTH(Text). For Happy Days, that is one to ten. There is no eleventh character.

Some programming languages start indices at zero. Use the convention required by the question; these examples deliberately use one-based positions.

05 | SUBSTRING NEEDS START AND LENGTH

Cambridge uses SUBSTRING(Text, Start, Length). Its result is a STRING containing the requested consecutive characters.

DECLARE Text : STRING
DECLARE Part : STRING
Text ← "Happy Days"
Part ← SUBSTRING(Text, 1, 5)
OUTPUT Part

Start at position one and take five characters: H, a, p, p, y. Part becomes "Happy".

The third argument is a count, not an ending position
ArgumentMeaning in this call
TextSource string: Happy Days
1Starting position
5Number of characters to extract

Start and length should be positive integers for this syllabus operation. We will use requests that stay within the source string, rather than assuming unspecified clipping or error behaviour.

06 | STARTING AT SEVEN DOES NOT MEAN TAKING SEVEN

To extract Days, start at position seven and take four characters.

Part ← SUBSTRING(Text, 7, 4)

The selected positions are seven, eight, nine and ten. The source Text is still Happy Days.

All calls assume Text holds Happy Days
Call using Happy DaysPositions selectedResult
SUBSTRING(Text, 1, 5)1 to 5"Happy"
SUBSTRING(Text, 7, 4)7 to 10"Days"
SUBSTRING(Text, 6, 1)6 only" "
SUBSTRING(Text, 5, 3)5 to 7"y D"

SUBSTRING(Text, 7, 10) would ask for ten characters starting at seven, not for characters seven through ten. That request extends beyond this ten-character source.

Always say the two roles aloud: “start here; take this many”. It prevents a common confusion with another language’s start/end slicing notation.

07 | TRY LENGTH AND EXTRACTION

Use ordinary letters, digits, punctuation and spaces in this demo. Try Happy Days with start seven and length four, then AB0072 with start three and length four.

The illustration labels spaces as SPACE. The result is shown with quotation marks so an extracted space is visible. Those surrounding display marks are not part of the extracted value.

08 | CALCULATE THE LAST POSITION INCLUDED

If an extraction starts at three and takes four characters, it covers three, four, five and six. Its last position is start plus length minus one.

LastPosition ← StartPosition + ExtractLength - 1

Subtract one because the starting position already counts as the first selected character. Three plus four gives seven, which would include one too many positions.

Start + length - 1 identifies the final included position
StartLengthLast position
155
7410
346
616

This calculation helps check whether the requested part fits inside the source. It does not change the meaning of the third SUBSTRING argument: that argument remains the number of characters.

09 | CHECK BEFORE EXTRACTING

A safe request in these examples needs StartPosition at least one, ExtractLength at least one, and its last position no greater than LENGTH(Text).

IF StartPosition >= 1 AND ExtractLength >= 1 AND (StartPosition + ExtractLength - 1) <= LENGTH(Text)
  THEN
    Part ← SUBSTRING(Text, StartPosition, ExtractLength)
    OUTPUT "Extracted part: ", Part
  ELSE
    OUTPUT "Extraction does not fit the text"
ENDIF

Assume declared STRING Text and Part, INTEGER positions and length, and usable integer values already supplied. The checks prevent the illustrated out-of-bounds requests.

An empty source has length zero, so no positive-length extraction can fit it. Handle that case rather than asking for character one of a nonexistent sequence.

Do not claim that every implementation automatically shortens an invalid request. Its behaviour is language-specific; write an algorithm whose valid requests are explicit.

10 | ONE CHARACTER EXTRACTED IS STILL A STRING

SUBSTRING returns STRING even if the requested length is one.

DECLARE Code : STRING
DECLARE FirstPart : STRING
Code ← "AB0072"
FirstPart ← SUBSTRING(Code, 1, 1)

FirstPart is the string "A". It is not automatically the CHAR literal 'A'. A single-character string and a CHAR can represent similar visible text while remaining different types in this notation.

Declare the receiving variable appropriately. The result of LENGTH is INTEGER, whereas the result of SUBSTRING is STRING.

That distinction matters when assigning results or explaining why a variable needs its type.

11 | EXTRACTION DOES NOT ALTER THE SOURCE

The operation produces a result; storing that result in Part does not remove it from the original text.

DECLARE Code : STRING
DECLARE Part : STRING
Code ← "AB0072"
Part ← SUBSTRING(Code, 3, 4)
OUTPUT Code
OUTPUT Part

The outputs are AB0072 and 0072. Code still contains all six characters, while Part holds the four-character result.

Part preserves its leading zeros because it remains text. It does not automatically become the integer seventy-two.

If you deliberately assign Code ← SUBSTRING(Code, 3, 4), Code is replaced by "0072" because of the assignment. The change is caused by choosing Code as the destination, not by extraction alone.

12 | BREAK DOWN A STRUCTURED IDENTIFIER

Suppose an identifier is defined as two group characters followed by four student characters. The complete code must be six characters before those parts are extracted.

DECLARE Code : STRING
DECLARE GroupPart : STRING
DECLARE StudentPart : STRING
OUTPUT "Enter a six-character code"
INPUT Code
IF LENGTH(Code) = 6
  THEN
    GroupPart ← SUBSTRING(Code, 1, 2)
    StudentPart ← SUBSTRING(Code, 3, 4)
    OUTPUT "Group: ", GroupPart
    OUTPUT "Student part: ", StudentPart
  ELSE
    OUTPUT "Code must contain six characters"
ENDIF

For AB0072, outputs are group AB and student part 0072. For AB72, the length check fails and extraction is skipped.

This checks only length. It does not prove that the first part contains letters, the second contains digits or the code identifies a real student. Those are additional requirements requiring additional checks.

13 | EXTRACT FROM THE END USING LENGTH

A string’s final position equals its length. To take its last two characters, start at LENGTH(Code) minus one and take two.

IF LENGTH(Code) >= 2
  THEN
    LastTwo ← SUBSTRING(Code, LENGTH(Code) - 1, 2)
ENDIF

Assume LastTwo and Code are STRING variables. For AB0072, the length is six, so the start is five and the result is "72". For X9, the start is one and the result is the whole "X9".

The guard excludes a source too short for the request. For a general positive extraction length k, the starting position of the final k characters is LENGTH(Code) - k + 1, provided the source has at least k characters.

Test a source exactly as long as the requested part, a longer source and a too-short source.

14 | TRACE LENGTH AND SUBSTRING TOGETHER

Assume Size is INTEGER and Text and Part are STRING
Instruction after Text ← "Happy Days"ResultSource Text afterwards
Size ← LENGTH(Text)Size = 10Happy Days
Part ← SUBSTRING(Text, 7, 4)Part = "Days"Happy Days
Size ← LENGTH(Part)Size = 4Happy Days
Text ← PartText becomes "Days"Days

The first operations read the source and store results elsewhere. Only the final assignment replaces Text.

To explain a result, identify the numbered characters involved rather than guessing from the word you expect to see. That habit helps with spaces, repeated letters and identifiers.

15 | COMMON MISTAKES AND PRECISE EXPLANATIONS

Spaces ignored: spaces are characters and count towards length and positions.

Positions begin at zero: these Cambridge examples use a first position of one.

Third argument treated as an end position: it is the number of characters to take.

Zero-length request assumed: the syllabus specifies positive start and length for SUBSTRING.

Source assumed to shrink: extraction returns a result; assignment determines which variable changes.

Numeric-looking text converted automatically: extracting 0072 preserves a string unless an appropriate conversion is specified.

A useful explanation is: “Start three and length four select positions three through six, so the substring is 0072. Code remains AB0072 because the result is assigned to another variable.”

The next lesson extends string handling with case conversion and further work on positions.

MATCH THE OPERATION TO ITS RESULT

Terminology

Terminology

String

An ordered sequence of zero or more characters.

Character

One text symbol, such as a letter, digit, punctuation mark or space.

String length

The number of characters in a string.

LENGTH

A Cambridge operation returning a string’s character count as INTEGER.

Substring

A consecutive part extracted from a string.

SUBSTRING

A Cambridge operation returning a specified-length string from a starting position.

Position

The numbered location of a character within the source.

One-based positions

A convention in which the first character is at position one.

Start position

The position of the first character to extract.

Extraction length

The number of consecutive characters to take, not an ending position.

Argument

A value supplied to an operation, such as the source, start or length.

Return value

The result produced by an operation for another instruction to use.

Empty string

A string containing no characters, written "".

Source string

The original text from which an operation reads.

Out-of-bounds request

An extraction that refers outside the available source positions.

Last included position

Start position plus extraction length minus one.

Leading zero

A zero at the beginning of text such as an identifier.

Length check

Validation of character count, separate from checking format or real-world accuracy.

Questions

Questions

CHECK YOUR UNDERSTANDING

Select all correct choices. Each exact set earns one point.

1. What does LENGTH return?
2. Which statements about literal "Happy Days" are correct?
3. Which statements distinguish "" and " "?
4. SUBSTRING(Text, 7, 4) with Text Happy Days returns which value?
5. Which statements describe the third SUBSTRING argument?
6. A substring starts at three and has length four. What is its final included position?
7. Part ← SUBSTRING(Code, 3, 4) with Code AB0072 does what?
8. Which are valid extraction conditions in these examples?

EXPLAIN AND COMPARE

Write your answers before revealing each sample.

1. Define string length and substring, and give an example of each.

2. Explain why LENGTH("A B") is three and LENGTH("") is zero.

3. Calculate SUBSTRING(Text, 5, 3) for Text Happy Days and show the positions.

4. Compare the roles of start and length in SUBSTRING(Code, 3, 4).

5. Explain why a one-character SUBSTRING result should be received by STRING rather than assuming CHAR.

6. Describe bounds checks for a general extraction with positive integer start and length.

7. Explain why extracting 0072 from AB0072 preserves leading zeros and does not remove it from Code.

8. Show how to extract the last two characters of a string safely.

BUILD IT | SPLIT A STUDENT CODE

Receive a six-character student code defined as a two-character prefix followed by a four-character student part. Check length before extraction. Output each part separately, or a clear length-error message. Write declarations and the complete algorithm. Trace ST0145 and, in a separate run, ST145. This task checks length and extraction only.

Reveal one possible solution
DECLARE StudentCode : STRING
DECLARE Prefix : STRING
DECLARE StudentPart : STRING
OUTPUT "Enter a six-character student code"
INPUT StudentCode
IF LENGTH(StudentCode) = 6
  THEN
    Prefix ← SUBSTRING(StudentCode, 1, 2)
    StudentPart ← SUBSTRING(StudentCode, 3, 4)
    OUTPUT "Prefix: ", Prefix
    OUTPUT "Student part: ", StudentPart
  ELSE
    OUTPUT "Student code must contain six characters"
ENDIF

ST0145 gives prefix ST and student part 0145. ST145 has length five, so the extraction branch is skipped and the error message appears.

Explain the limit: a six-character length alone does not prove that the prefix contains letters, the final part contains digits or the code belongs to a real student.

Flashcards

Flashcards

Click to flip. Select the ideas you need to revisit.

0 cards selected for revision.

    Selections are kept while this page is open.

    Workbook

    Workbook

    COMING SOON

    The workbook for 8.1.4E.1 String Length and Substrings is coming soon. Complete the matching task and written questions in your exercise book.