A substring is a consecutive sequence of characters extracted from a string. You extract one by specifying its starting position and boundary or length, then manipulate it using operations such as concatenation, replacement, or case conversion.
The process depends on the programming language, but the underlying mechanism is the same:
- Determine the index of the first required character.
- Determine where extraction should stop.
- Apply slicing or a substring function.
- Store or manipulate the extracted value.
For example, in Python:
text = "COMPUTER"
part = text[3:6]
Python uses zero-based indexing, so index 3 contains P. The ending index 6 is excluded, meaning part becomes "PUT" from indices 3, 4, and 5.
| Operation | Python example | Result |
|---|---|---|
| Extract | text[3:6] | "PUT" |
| Convert case | text[3:6].lower() | "put" |
| Replace a section | text[:3] + "POS" + text[6:] | "COMPOSER" |
| Test membership | "PUT" in text | True |
Concatenation joins strings together. It is often used to reconstruct a string after changing one section. In languages such as Python and Java, strings have immutability, meaning their characters cannot be changed directly; an operation instead creates a new string.
Different languages use different syntax. Python uses text[start:end], while Java uses text.substring(start, end). In both cases, the start is included and the end is excluded.
A common misconception is that the ending index is included. This causes an off-by-one error, so always trace the exact indices selected and check the language's boundary rules.
For IB Computer Science B2.1 questions, an examiner may ask you to trace string operations, construct code, or determine output. Show index positions clearly, state whether the end boundary is excluded, and preserve the original character order.