String Manipulation
Working with text
Programs constantly handle text — names, passwords, messages. String manipulation means examining and changing that text. A string is a sequence of characters, each with a position (index), usually starting at 0.
For the string "HELLO": H=0, E=1, L=2, L=3, O=4.
Length
length() gives the number of characters in a string.
length("HELLO")= 5.- Spaces and punctuation count too:
length("Hi!")= 3.
Getting part of a string (substrings)
You can pull out a section of a string. Exact syntax varies by board/language, but the idea is the same:
- A single character by index:
"HELLO"[1]→"E". - A substring using a start position and length or a range, e.g.
substring("HELLO", 1, 3)→"ELL"(3 characters from index 1).
Joining strings (concatenation)
Concatenation joins strings together, usually with +:
first = "Ada"
last = "Lovelace"
full = first + " " + last // "Ada Lovelace"
Changing case
upper()/toUpper()converts to CAPITALS:upper("hi")→"HI".lower()/toLower()converts to lower case:lower("Hi")→"hi".- Useful for comparisons (so "YES", "Yes" and "yes" all match).
Converting between types (casting)
Numbers typed in are often read as strings and must be converted before doing maths:
int("25")→ the integer 25 (now you can add to it).str(25)→ the string "25" (now you can join it to text).float("3.5")→ the real number 3.5.
Trying to do "25" + 3 may join text or cause an error — convert first.
Worked example
Given word = "Computer", what do these give?
1. length(word) → 8.
2. word[0] → "C".
3. upper(word) → "COMPUTER". ✓
Common mistakes
- Forgetting strings are usually 0-indexed (the first character is index 0).
- Adding a string and a number without converting — causes errors or joins them as text.
- Forgetting spaces/punctuation are counted by
length().
Exam tips
- Learn the common operations: length, substring/index, concatenation, upper/lower, and casting (int/str).
- Watch indexing carefully in trace questions — start at 0.
- If input maths goes wrong, suspect a string that needs converting to a number.
Key facts to remember
- Strings are indexed from 0;
length()counts every character including spaces. - Concatenation (
+) joins strings; substring/index extracts parts; upper/lower change case. - Casting converts between strings and numbers (
int(),str(),float()) — essential before maths on input.