Table of Contents
1. Replacing Text
replace(): Simple Character/String Replacement
Replace all occurrences of a character or literal substring:
String text = "apple-banana-orange";
String replaced = text.replace("-", ", ");
// "apple, banana, orange"
replaceAll() & replaceFirst(): Regex-Based Replacement
replaceAll(String regex, String replacement): Replace all regex matches.
String data = "Error: 404; Error: 500";
String cleaned = data.replaceAll("Error: \\d+", "OK");
// "OK; OK"
replaceFirst(String regex, String replacement): Replace only the first match.
String log = "[WARN] Disk full. [WARN] Low memory.";
log = log.replaceFirst("\\[WARN\\]", "[INFO]");
// "[INFO] Disk full. [WARN] Low memory."
Key Difference:
replace()works with literals.replaceAll()/replaceFirst()use regex (slower for simple cases).
2. Splitting Strings
split(String regex): Divide a String into an array using regex.
String csv = "Java,Python,C++,JavaScript";
String[] langs = csv.split(", "); // ["Java", "Python", "C++", "JavaScript"]
Handling Special Characters: Escape regex symbols like ., |, or $:
String path = "file.name.txt";
String[] parts = path.split("\\."); // ["file", "name", "txt"]
Limiting Splits: Optional limit parameter restricts the number of splits:
String data = "one:two:three:four";
String[] result = data.split(":", 2); // ["one", "two:three:four"]
3. Joining Strings
String.join() (Java 8+): Concatenate elements with a delimiter.
List<String> list = Arrays.asList("Java", "C#", "Python");
String joined = String.join(" | ", list); // "Java | C# | Python"
Use Case: Building CSV lines or URLs:
String[] params = {"sort=asc", "page=2"};
String url = "https://api.com/data?" + String.join("&", params);
4. Converting Between Types
String ↔ char[]
// String to char[]
char[] chars = "Hello".toCharArray();
// char[] to String
String s = new String(chars);
String ↔ byte[] (with Encoding)
// String to UTF-8 bytes
byte[] bytes = "text".getBytes(StandardCharsets.UTF_8);
// byte[] to String
String restored = new String(bytes, StandardCharsets.UTF_8);
Other Conversions
// String to int
int num = Integer.parseInt("42");
// int to String
String s = Integer.toString(42); // or String.valueOf(42)
Caution: Handle NumberFormatException for invalid parses.
Common Mistakes
❌ Forgetting Immutability:
String s = "hello";
s.replace("h", "H"); // Original unchanged!
s = s.replace("h", "H"); // ✅
❌ Unescaped Regex in split():
"a|b|c".split("|"); // Incorrect! Splits every character.
"a|b|c".split("\\|"); // ✅ ["a", "b", "c"]
FAQ
Why does replaceAll("\\d", "X") replace all digits?
\\d is a regex pattern for digits. Use replace() for literal replacements.
How to split by whitespace?
Use split("\\s+") to handle multiple spaces/tabs.
Is String.join() better than StringBuilder for small lists?
Yes – it’s concise and optimized under the hood.