String
Overview
A String is a non-primitive data type that represents a sequence of characters. Strings are used to store and manipulate text, from a single word to entire documents.
They are one of the most frequently used data types in software systems.
What Is a String?
A string is:
- An ordered collection of characters
- Often immutable (language dependent)
- Stored as a contiguous or semi-contiguous sequence
Strings are usually encoded using Unicode.
How It Works
Internally, a string may store:
- A character array
- Length metadata
- Encoding information
Access is index-based, similar to arrays.
Common Operations
| Operation | Time Complexity |
|---|---|
| Access | O(1) |
| Concatenation | O(n) |
| Substring | O(n) or O(1)* |
| Comparison | O(n) |
| Search | O(n) |
* Depends on implementation.
Example
Pseudocode
msg = "Hello, World"
print(msg[0]) // 'H'
Real-world Analogy
A string is like a necklace of characters. Each bead matters, and the order defines the meaning 📿.
Use Cases
- User input and output
- Text processing
- File handling
- Network protocols
- Identifiers and labels
Advantages
- Natural representation of text
- Rich built-in operations
- Unicode support
Limitations
- Concatenation can be expensive
- Immutability may cause overhead
- Encoding issues across systems
String vs Character Array
| Aspect | String | Character Array |
|---|---|---|
| Mutability | Often immutable | Mutable |
| Safety | High | Lower |
| Convenience | High | Lower |