Course contentsShow
← Java
Lesson 2205 of 2,87043. String Handling in DepthFree lesson

Combining substring, indexOf, and replace for String Parsing

Apply these methods together to extract, locate, and transform data within strings effectively.

Combining substring, indexOf, and replace for String Parsing

You'll learn how to chain substring(), indexOf(), and replace() methods to extract, locate, and transform data within complex strings.

The Power of Method Composition

Now that you've mastered substring(), indexOf(), and replace() individually, the real magic happens when you combine them. Think of it like using multiple tools from a toolbox together—a hammer and nails work fine separately, but together they build something useful.

Parsing Real-World Data

Imagine parsing an email address like "user@example.com". You might:

  1. Use indexOf() to locate the @ symbol
  2. Use substring() to extract the username and domain separately
  3. Use replace() to sanitize or normalize the parts
String email = "john.doe@example.com";
int atIndex = email.indexOf('@');

if (atIndex != -1) {
    String username = email.substring(0, atIndex);
    String domain = email.substring(atIndex + 1);
    
    // Normalize username: replace dots with underscores
    String normalized = username.replace('.', '_');
    
    System.out.println("User: " + normalized);  // User: john_doe
    System.out.println("Domain: " + domain);    // Domain: example.com
}

Extracting Between Delimiters

You can also extract content between markers:

String data = "Name: [Alice Smith], Age: [30]";
int start = data.indexOf('[') + 1;
int end = data.indexOf(']');

String name = data.substring(start, end);
System.out.println(name);  // Alice Smith

Then use indexOf() with an offset to find the next bracket pair and repeat the pattern.

Key Takeaway: Combining substring(), indexOf(), and replace() creates powerful string parsing solutions—use indexOf() to locate delimiters, substring() to extract parts, and replace() to clean or transform the results.