Java
String Manipulation
Substring
Programming
Coding Techniques

Java Getting a substring from a string starting after a particular character

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

String manipulation in Java is both an art and a science, providing developers a variety of tools for handling text-based data. One common requirement is extracting a substring from a string, starting immediately after a particular character. Whether you're parsing file paths, handling user input, or simply working with textual data, understanding how to extract and manipulate substrings efficiently is essential.

Substrings in Java

In Java, the String class includes the substring() method, allowing developers to carve out portions of a string with precision. The basic syntax for the substring() method is:

java
String substring(int beginIndex, int endIndex)
  • beginIndex: The starting index, inclusive.
  • endIndex: The ending index, exclusive.

If you only provide the beginIndex, it will extract from that index to the end of the string.

Extracting After a Particular Character

To extract a substring starting after a specific character, you'll often use the indexOf() method in tandem with substring(). The indexOf() method returns the index of the first occurrence of a specified character or substring.

Here's a step-by-step example of how you might do this:

Example: Extracting Username from an Email Address

Suppose you have an email address, and you want to extract the username part (characters after '@').

java
1public class SubstringExample {
2    public static void main(String[] args) {
3        String email = "[email protected]";
4        char specialChar = '@';
5        
6        // Find the position of the special character
7        int specialCharIndex = email.indexOf(specialChar);
8        
9        if (specialCharIndex >= 0 && specialCharIndex < email.length() - 1) {
10            // Get the substring starting after the special character
11            String substring = email.substring(specialCharIndex + 1);
12            System.out.println("Extracted substring: " + substring);
13        } else {
14            System.out.println("Character not found or no text after character.");
15        }
16    }
17}

Explanation

  1. Find the Special Character: We use indexOf('@') to find the position of the character @. If the indexOf() method returns -1, the character is not present.
  2. Extract the Substring: If specialCharIndex is valid, use substring(specialCharIndex + 1) to capture everything following the '@'.

Handling Edge Cases

  • Character Not Found: Always check if indexOf() returns -1.
  • Empty Result: If specialChar is the last character of the string, ensure no attempt to access beyond string length.
  • Null or Empty String: Before processing, verify the string is not null or empty.

Advanced Usage

Extracting with Delimiters

To handle strings where you have multiple delimiters, you might want to use regex or split() method for more powerful parsing capabilities. For example, extracting domains from multiple email addresses:

java
1import java.util.regex.*;
2
3public class RegexExample {
4    public static void main(String[] args) {
5        String emails = "[email protected], [email protected]";
6        String regex = "(?<=@)[\\w.]+";
7        
8        Pattern pattern = Pattern.compile(regex);
9        Matcher matcher = pattern.matcher(emails);
10        
11        while (matcher.find()) {
12            System.out.println("Domain: " + matcher.group());
13        }
14    }
15}

Explanation

  • Regex: Lookbehind pattern (?<=@) finds positions after @, capturing domain parts without in-line parsing logic.

Performance Considerations

Substrings may slightly impact performance if processed in bulk due to string immutability in Java. Always balance readability and efficiency, opting for StringBuilder when significant concatenation is needed.

Summary Table

ConceptDescription
indexOf()Finds the index of a character or substring. Returns -1 if not found.
substring()Extracts a part of the string from begin index to end index.
Advanced ExtractionUse regex or split() for complex delimiters.
Edge CasesHandle null/empty strings and ensure the special character exists before extracting.
PerformanceString manipulations can impact performance. Use alternatives like StringBuilder for heavy processing.

Conclusion

String manipulation is a core part of Java programming, and extracting substrings based on specific characters is a common task. By leveraging Java’s robust string methods, developers can efficiently parse and process text data, making their applications more powerful and adaptive. Whether using basic substring() functions or advanced regex, understanding these methods' capabilities and limitations is essential for effective Java programming.


Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.