Need a discount on popular programming courses? Find them here. View offers

Java and Code


Disclosure: Hackr.io is supported by its audience. When you purchase through links on our site, we may earn an affiliate commission.



How to Extract a Java Substring [with Code Examples]

Posted in Java , Code
How to Extract a Java Substring

The Java String data type uses a sequence of characters (char data types) to store all sorts of text-like data. As one of the most widely used data types, strings are often the focus of Java coding interview questions via string manipulation problems, whether that be string reversal, conversion, string splitting, or extracting substrings.

When it comes to Java, we have access to a range of string methods that are part of the String class. This tutorial provides various code examples and walkthroughs for the built-in Java substring method .substring() to extract a Java Substring.

Note: The methods we cover in this article were coded with Java 11.

How To Extract a Java Substring

Substrings represent an ordered sequence of characters that we can extract from a Java String object. Due to the string data type’s immutability property, we will have to store any substring in Java that we extract from an existing String object in a new String variable.

For example: If we have the Java String: “Learn Java on Hackr.io”, we could extract the substring “Hackr.io”. To do this, we’d need to store it in a new String object, meaning that we don’t modify the original String. This applies to any sequenced subsection of our original string: we could extract “Lear”, “Java”, “on Hac”, etc.

With Java, we have access to a built-in .substring() method as part of the Java String class. And luckily for us, this method is super simple to use as it only requires start and end index arguments. The result is a delimited portion of the originalString in a new String object, namely the Substring.

Another way to extract substrings in Java is with the built-in .split() method (also part of the Java String class). This method splits a String into one or more substrings separated by a delimiting character (space, comma, char value, etc.), and returns the substrings in an array. 

While this can be useful in some scenarios, it’s less suited to extracting specific excerpts from existing strings than the .substring() method.

How To Use Java .substring() Method

The Java .substring() method extracts a substring from an existing string based on index values we pass in as integer arguments.

Syntax for Java .substring()

We can use the .substring() method in one of two ways.

The first approach returns a substring as a new String object formed by chars between the start index value (inclusive) and the end of the original string.

String strEx = new String("Example");
String subStr = strEx.substring(int startIndex);

 

The second way returns a substring as a new String object formed by chars from the start index, up to but not including the end index, in the original string.

String strEx = new String("Example");
String subStr = strEx.substring(int startIndex, int endIndex);

 

Note: both approaches throw an IndexOutOfBoundException exception if we pass in start index values that are greater than the original string length, or less than 0. We’ll also throw this error if the start index is greater than the end index.

Let’s look at some code examples using the Java .substring() method.

Java Substring Example Using Index Values

In this example, we’ll create a String object (‘Learn Java on Hackr.io’) which we can use as a base to extract a range of substrings. We’ll then pass integer index values to Java’s built-in substring() method.

Firstly, we’ve passed in a start index value of 0 with no end index, which effectively returns the original string, as shown in the output.

Secondly, we’ve passed in a start and end index value, with the end index representing the length of the original string. Now, because Java uses zero-indexing and the end index is non-inclusive, this also returns the full original string, as you can see in the output.

This means that the first two snippets were equivalent ways to return the same substring, namely the original string.

Next, we passed in a start index value of 1, which trims the first char from the original string to produce a substring. We then passed in a start index of 0 and an end index of n-1, which trims the last char from the original string for the substring, as shown in the output. 

Finally, we’ve passed arbitrary start and end index values to return different substrings, as shown in the output. Note that blank spaces are also valid chars, which means we can return these within a substring, as shown in the last substring example.

public class SubstringHackrIO {
  public static void main(String[] args) {
    String strExample = "Learn Java on Hackr.io";
    System.out.println("Original string: " + strExample);

    // Find length of string: n = 25
    int n = strExample.length();
    
    // Extract and print substrings
    System.out.println("From index 0: " + strExample.substring(0));
    System.out.println("From index 0 to n: " + strExample.substring(0, n));
    System.out.println("From index 1: " + strExample.substring(1));
    System.out.println("From index 0 to n-1: " + strExample.substring(0, n-1));
    System.out.println("From index 0 to 10: " + strExample.substring(0, 10));
    System.out.println("From index 10 to 14: "+ strExample.substring(10, 14));
  }
}​

 

Output:

Original string: Learn Java on Hackr.io
From index 0: Learn Java on Hackr.io
From index 0 to n: Learn Java on Hackr.io
From index 1: earn Java on Hackr.io
From index 0 to n-1: Learn Java on Hackr.i
From index 0 to 10: Learn Java
From index 10 to 14:  on

How To Print Part of a String in Java With .indexOf()

In this example, we are using Java’s built-in .indexOf() method to extract a substring between two distinct characters, namely opening and closing square brackets.

Syntax for .indexOf() 

String strEx = new String("Example");
int indexVal = strEx.indexOf("x"); // indexVal = 1

 

This approach can be useful as it can be more intuitive to extract substrings based on their proximity to other chars rather than passing in substring index values.

So, by passing the open square bracket as a String argument to .indexOf(),we can return the index value for the first occurrence of this char in the original String. This will be our start index in this substring Java example.

Next, we can pass the closing square bracket as a String argument to indexOf(), which returns the index value for the first occurrence of this char in the original String. We will use this as the end index value to extract the substring.

Recall that the start index is inclusive, and the end index is non-inclusive. This means we must shift the start index by +1 to start our substring at the first char to the right of the open square bracket. The end index is ready to go, as it will return the first char to the left of the closing square bracket.

Finally, as shown in the output, we can use the start and end index values with .substring() to extract and print our substring.

public class SubstringHackrIO {
  public static void main(String[] args) {
    String strExample  = "Learn Java on [Hackr.io]";
    System.out.println("Original string: " + strExample);

    // Get index values for first occurrences of '[' and ']'
    int start = strExample.indexOf("[");
    int end = strExample.indexOf("]");

    // Extract and print substring between '[' and ']'
    String subStr = strExample.substring(start + 1, end);
    System.out.println("Substring: " + subStr);
  }
}​

 

Output:

Original string: Learn Java on [Hackr.io]
Substring: Hackr.io​

 

Java Substring Method Using .lastIndexOf()

For this example, we’ll use Java’s .indexOf() and .lastIndexOf() methods. We’ll pass substring arguments to these methods this time rather than individual chars.

Syntax for .lastIndexOf() 

String strEx = new String("Example Example");
int indexVal = strEx.lastIndexOf("x"); // indexVal = 9

 

We’ll start by using .indexOf() to find the index for the first char in the first occurrence of the substring, ‘Learn’. This will be the index for the char, ‘L’.

We’ll then use .lastIndexOf() to find the index value for the first char in the last occurrence of the substring, ‘Java’, which will be the index for ‘J’.

If we use those two results as our start and end index values, we can extract a substring of chars from the start index (inclusive), up to but not including the end index. We can now pass these arguments to .substring(), before printing the result, as shown in the output.

Note: if we cannot find a substring using .indexOf() or .lastIndexOf(), the return value will be -1. You should consider handling this possibility in production code, as it could cause an exception with .substring()

public class SubstringHackrIO {
  public static void main(String[] args) {
    String strExample = "Learn Java on Hackr.io, and enjoy Java!";     
    System.out.println("Original string: " + strExample);

    // Get index of first occurrence of "Learn" substring
    int start = strExample.indexOf("Learn");
    // Get index of last occurrence of "Java" substring
    int end = strExample.lastIndexOf("Java");

    // Extract and print substring
    String subStr = strExample.substring(start, end);
    System.out.println("Substring: " + subStr);
  }										
}​

 

Output:

Original string: Learn Java on Hackr.io, and enjoy Java!
Substring: Learn Java on Hackr.io, and enjoy

Conclusion

In this tutorial, we’ve covered various substring functions in Java that you can use to extract a Java Substring from an existing String object with the built-in .substring() method.

We started with simple examples that used index values for either the start position or the start and end positions to help us extract substrings from an original String.

We then explored Java’s .indexOf() and .lastIndexOf() methods to return a substring from an original string by searching for char values.

This ‘char search’ approach enabled us to find the index of our desired chars (or substrings) within the original stringobject, thus allowing us to extract substrings without explicitly declaring index values. This approach can be more intuitive if you can visually see the words or chars surrounding the substring you’d like to extract.

Want to take your Java development to the next level?

Check Out Our Java Cheat Sheet

Or This list Of Java Projects

Frequently Asked Questions

1. What Does .substring(1) Do in Java?

This returns a new substring object equivalent to trimming the first char from the original string.

2. How Do You Substring in Java?

You can use the .substring() method with either a start index or start and end index values to return a substring from an original string in Java. Note that the end index value is non-inclusive, which means the substring will be up to but not including the char at this index.

3. Can .split() be Used to Make Substrings in Java?

You can use the Java .split() method to split a string into an array of substrings originally separated in the string by a delimiting value (comma, space, char, etc.).

4. How Do I Split a String Into a Substring? 

The Java String class provides the .substring() method that you can use to extract a substring from an original string. Alternatively, you can use the built-in .split() method to split a string into an array of substrings originally separated by a delimiting value (comma, space, char, etc.).

Leave a comment

Your email will not be published
Cancel