Topic 8 Β· Programming Β· 8.10

String Manipulation Explained Simply

String manipulation means working with text. Two important routines are LENGTH, which counts characters, and SUBSTRING, which extracts part of a string.

Invitation

How can a program work with text?

A string stores text such as a name, password, product code or sentence.

String manipulation means examining or changing that text. Programs often need to count its characters or take out one section.

LENGTH counts characters. SUBSTRING selects characters.
Figure 1
Working with a string
"COMPUTER"
↓
Count it
Select part of it
Big Idea

Strings are made from individual characters

The string "CODE" contains four characters: C, O, D and E.

Spaces also count as characters. The string "Hello Sam" contains nine characters because the space is included.

A character can be a letter, number, symbol or space.
Figure 2
Characters inside a string
C   O   D   E
↓
4 characters
FutureLogic Bridge

String manipulation is like editing a sentence

Imagine highlighting text in a document. You can count how many characters are present, or highlight only the section you need.

LENGTH is like checking the character count. SUBSTRING is like highlighting and copying part of the text.

Count the text, or select a section of the text.
Figure 3
The editing bridge
Full text: COMPUTER
↓
Highlight: PUT
Take only the characters you need.
Worked Example

Use LENGTH and SUBSTRING

The program stores the word COMPUTER, finds its length and extracts the first three characters.

PseudocodeString routines
Word <- "COMPUTER"
NumberOfCharacters <- LENGTH(Word)
FirstPart <- SUBSTRING(Word, 1, 3)
OUTPUT NumberOfCharacters
OUTPUT FirstPart
PythonEquivalent idea
word = "COMPUTER"
number_of_characters = len(word)
first_part = word[0:3]
print(number_of_characters)
print(first_part)

Follow the routines

COMPUTERThe original string
8LENGTH counts all characters
COMSUBSTRING extracts characters 1 to 3
Outputs: 8 and COM
Exam Tip

Read the SUBSTRING values carefully

In Cambridge-style pseudocode, SUBSTRING(Text, Start, Length) means:

Text = the original string
Start = the first character position
Length = how many characters to take

For example, SUBSTRING("PASSWORD", 1, 4) returns "PASS".

Common Mistake

Forgetting that spaces count

Students sometimes count only the visible letters and ignore spaces.

Incorrect: LENGTH("Hello Sam") = 8
Correct: β€œThe space is also a character, so the length is 9.”

Also remember that Python normally starts character positions at zero, while Cambridge pseudocode examples usually start at one.

Summary

The string manipulation pattern

StringText stored inside quotation marks.
CharacterOne letter, digit, symbol or space.
LENGTHCounts all characters.
SUBSTRINGExtracts part of a string.
StartThe first character position to use.
LengthThe number of characters to extract.