Strings are character arrays ending with \0. Most operations are O(n). Mutable strings change in place; immutable strings create new instances. Common pitfalls include forgetting \0, confusing length with size, and using == instead of equals().
Trap: Assuming 'ABC' takes 3 bytes (it takes 4 with \0). Trap: Using == in Java compares memory addresses, not content. Always use .equals() for string comparison.
Assuming "ABC" takes 3 bytes. Nope! It takes 4.
(A, B, C, \\0).
Always remember: Length + 1 = Memory Size
In Java/JS, == checks if they are the same object in memory. Use .equals() or === to check the text!
1// WRONG (Java)2if (str1 == str2) { ... } // Compares addresses!34// RIGHT5if (str1.equals(str2)) { ... } // Compares content67// RIGHT (JavaScript)8if (str1 === str2) { ... } // Compares content
Creating a character array without \\0 causes functions to read past your data, showing garbage memory or crashing.
1// DANGEROUS2char arr[] = {'H', 'E', 'L', 'L', 'O'}; // No \0!3printf("%s", arr); // May print garbage45// SAFE6char str[] = "HELLO"; // Includes \0 automatically
| Operation | Time | Space |
|---|---|---|
| Length | O(n) | O(1) |
| Compare | O(n) | O(1) |
| Concatenate | O(n) | O(n) |
| Storage | - | O(n) |
Let's review the key points and common mistakes.
The Essentials
1. String = Char Array + \0: Strings are arrays with a terminator
2. Length vs Size: Length = characters before \0, Size = length + 1 (includes \0)
3. Operations = O(n): Most operations traverse the string
4. Mutable vs Immutable: Know which your language uses
Common Pitfalls
Trap #1: The Phantom Byte
Assuming "ABC" takes 3 bytes. Wrong! It takes 4:
Total: 4 bytes
Trap #2: == vs equals()
In Java/JavaScript:
== checks if variables point to the SAME object in memory.equals() checks if the TEXT content is the sameTrap #3: Missing Null Terminator
Creating a character array without \0:
Trap #4: Off-by-One Errors
Quick Reference
Quick reference for interviews and avoiding common bugs. These mistakes cause buffer overflows, incorrect comparisons, and memory issues.
"What are common mistakes when working with strings?"
Forgetting the null terminator, confusing length with memory size, using == instead of equals() for comparison, and off-by-one errors when accessing string indices.