Strings (Encoding, Immutability)
A String is a data type used in programming to represent text rather than numbers. It is comprised of a set of characters that can also contain spaces and numbers.
1. The Core Concept
Under the hood, a string is essentially an array of characters.
"Hello"is conceptually['H', 'e', 'l', 'l', 'o'].- However, modern languages treat them as a distinct primitive type with special methods (like
substring,replace,toUpperCase).
2. Character Encoding
Computers only understand binary (0s and 1s). To store text, we map every character to a number. This mapping is called Encoding.
ASCII (American Standard Code for Information Interchange)
- Size: 7 bits (128 characters).
- Scope: English letters (A-Z, a-z), digits (0-9), and basic punctuation.
- Limitation: Cannot represent accents (é, ñ) or non-Latin scripts (Chinese, Arabic).
Unicode & UTF-8
Unicode is a universal character set that assigns a unique number (Code Point) to every character in every language (and emojis).
- UTF-8: The most common encoding for Unicode. It is variable-width:
- Standard ASCII characters take 1 byte.
- Accented characters take 2 bytes.
- Asian characters take 3 bytes.
- Emojis take 4 bytes.
3. Immutability
In many modern languages (Java, Python, C#, JavaScript), strings are Immutable.
- Meaning: Once a string object is created, it cannot be changed.
- Modification: When you "modify" a string (e.g.,
str + " world"), you are actually creating a new string object in memory. The old one remains unchanged (until garbage collected).
# Python Example
s = "Hello"
s[0] = "J" # Error! Strings are immutable.
s = "Jello" # This creates a NEW string and points 's' to it.
Why Immutability?
- Security: Strings are often used for database connections, URLs, and passwords. If they were mutable, a malicious thread could change the connection string after security checks passed.
- Thread Safety: Immutable objects are inherently thread-safe. Multiple threads can read the same string without locking.
- String Pool (Interning): Since strings can't change, the runtime can save memory by storing only one copy of duplicate strings (e.g., "Hello") and having multiple variables point to it.
4. Mutable Strings (String Builders)
Because string concatenation creates new objects, doing it in a loop is very inefficient ($O(N^2)$).
To solve this, languages provide mutable string classes:
- Java:
StringBuilder/StringBuffer - C#:
StringBuilder - Python: Use a list of strings and then
''.join(list).
// Java StringBuilder
StringBuilder sb = new StringBuilder("Hello");
sb.append(" World"); // Modifies the existing object (Fast)
programming/common-syntax programming/arrays-and-lists programming/integers