Strings
Task: Reverse this string in place
Why we need Strings
Analogy
- Imagine a necklace made of beads.
- Each bead is a character, and together they form a string.
- You can count the beads, replace one, or cut the necklace into smaller parts.
What is a string?
Definition
A string is a sequence of characters stored together.
"Hello" is made up of 'H', 'e', 'l', 'l', 'o'.
Strings are how programs represent text.
String operations
| Operation | What it does | Example |
|---|---|---|
| Concatenation | Joins two strings | "Hello" + "World" |
| Substring | Takes part of a string | "Hello"[0:2] |
| Length | Counts the characters | len("Hello") |
| Search | Finds a character or word | "World" in "HelloWorld" |
Try it yourself
A run of characters you can read, not rewrite
"Hello"Choose an operationPress concat and watch every character flash, not just the new one. Then press edit, which is the one that will not work. Both of those have a reason, further down the page.
Example in code
s = "Hello" print(len(s)) # 5print(s.upper()) # HELLOprint(s[1]) # eprint(s + " World") # Hello WorldImmutable nature
In many languages, including Python and Java, strings are immutable. Once a string is created it cannot be changed directly.
Watch out
"Hello"[0] = 'J' is an error, not an edit. To get "Jello" you have to build a new string.
So an operation that looks like a change is really a replacement: the variable is pointed at a fresh string, and the old one is left behind untouched.
That rule has an upside. Because the characters can never change, a language is free to let two variables share one stored copy instead of giving each its own.
Advantages
- Easy to represent text and data.
- A rich set of built-in operations comes for free.
- The foundation for parsing, searching and data handling.
Limitations
- Immutable strings are inefficient when you modify them repeatedly, because each change builds a whole new string.
- Large string operations can use a lot of memory.
Strings vs arrays
| Array | String | |
|---|---|---|
| Elements | Numbers or objects | Characters |
| Mutability | Often mutable | Often immutable |
| Use case | Store a collection | Represent text |
Note
A string behaves like an array of characters that you are not allowed to write into. Reading by index works the same way, and it starts at 0 the same way.
Quick recap
Think of a sentence in a book. Each letter is a character, and together they form words and sentences.
- A string is a sequence of characters
- Operations: concatenate, substring, length, search
- Immutable in many languages, so a change builds a new string
- Used everywhere text is needed
Key takeaway
Beads on a necklace, and in most languages the necklace cannot be restrung.