Lesson Completion
Back to course

String Modification Methods: Transform and Clean Text

Beginner
15 minutes4.7JavaPlay to Learn

1. The Hook (The "Byte-Sized" Intro)

  • In a Nutshell: String modification methods return new strings (immutability!).
  • Common operations: replace, trim, strip, case conversion, and character removal.

When Instagram sanitizes usernames: input.trim().toLowerCase().replace(" ", "_"). Clean, standardized output!


2. Quick Reference

MethodPurpose
replace(old, new)Replace all occurrences
replaceAll(regex, new)Replace using regex
replaceFirst(regex, new)Replace first match only
trim()Remove leading/trailing spaces
strip()Remove whitespace (Java 11+, Unicode-aware)
toLowerCase()Convert to lowercase
toUpperCase()Convert to uppercase

3. Interactive & Applied Code

java
public class StringModification { public static void main(String[] args) { // === REPLACE === String text = "Hello World"; System.out.println(text.replace('o', '0')); // "Hell0 W0rld" System.out.println(text.replace("World", "Java")); // "Hello Java" // Replace all with regex String numbers = "a1b2c3"; System.out.println(numbers.replaceAll("[0-9]", "")); // "abc" // Replace first only String repeat = "aaa"; System.out.println(repeat.replaceFirst("a", "b")); // "baa" // === TRIM / STRIP === String padded = " Hello "; System.out.println(padded.trim()); // "Hello" System.out.println(padded.strip()); // "Hello" (Java 11+) System.out.println(padded.stripLeading()); // "Hello " System.out.println(padded.stripTrailing()); // " Hello" // === CASE CONVERSION === String mixed = "HeLLo WoRLd"; System.out.println(mixed.toLowerCase()); // "hello world" System.out.println(mixed.toUpperCase()); // "HELLO WORLD" // === CHAINING MODIFICATIONS === String username = " John Doe "; String clean = username.trim() .toLowerCase() .replace(" ", "_"); System.out.println(clean); // "john_doe" // === REMOVE CHARACTERS === String withDigits = "abc123def456"; String lettersOnly = withDigits.replaceAll("[0-9]", ""); System.out.println(lettersOnly); // "abcdef" String withSpaces = "hello world java"; String noSpaces = withSpaces.replace(" ", ""); System.out.println(noSpaces); // "helloworldjava" // === REAL-WORLD: Clean phone number === String phone = "(123) 456-7890"; String digits = phone.replaceAll("[^0-9]", ""); System.out.println(digits); // "1234567890" // === REAL-WORLD: Slug generator === String title = " Hello World! @2024 "; String slug = title.trim() .toLowerCase() .replaceAll("[^a-z0-9\\s]", "") .replace(" ", "-"); System.out.println(slug); // "hello-world-2024" } }

⚠️ Common Mistakes

Mistake #1: Forgetting immutability

java
String s = " hello "; s.trim(); // ❌ Result discarded! s = s.trim(); // ✅ Reassign

Mistake #2: Confusing replace() and replaceAll()

java
"a.b.c".replace(".", "-"); // "a-b-c" (literal) "a.b.c".replaceAll(".", "-"); // "-----" (. is regex wildcard!) "a.b.c".replaceAll("\\.", "-"); // "a-b-c" (escaped)

4. The "Interview Corner"

🏆 Q1: "trim() vs strip()?" Answer: trim() removes ASCII whitespace (char <= 32). strip() (Java 11+) removes all Unicode whitespace including special spaces.

🏆 Q2: "How to remove all non-alphanumeric characters?"

java
str.replaceAll("[^a-zA-Z0-9]", "");

🎓 Key Takeaways

✅ All methods return new strings
replace() is literal, replaceAll() is regex
✅ Chain methods for complex transformations
strip() is better than trim() (Java 11+)

Topics Covered

Java FundamentalsStrings

Tags

#java#strings#string-manipulation#string-methods#beginner-friendly

Last Updated

2025-02-01