How to remove a prefix from a string in Java

In this tutorial, we are learning how to remove a prefix from a string in Java. We can remove a prefix from a string using the substring method.

Also read: How to remove leading zeros from a string in Java

Using substring() method

This method is defined in the String class of java.lang package. It has two parameters, the first parameter is the starting index which is mandatory and the second parameter is the ending index.

public String substring(int startIndex):
String s="CodeSpeedy"; 
System.out.println(s.substring(4));

The output looks like this:

Speedy

In the above program without giving an ending index I have used the substring method.

Using substring method with two parameters.

public String substring(int startingIndex, int endingIndex)
String s="CodeSpeedy"; 
System.out.println(s.substring(0,4));

The output looks like this:

Code

The first parameter is for starting index which is taken inclusive and the second parameter is the ending index which is taken exclusive.

Using substring for removing a prefix from a string

We can put any substring that we want to remove from our string with the below piece of code.

String s="CodeSpeedy";
String sub="Code";
System.out.println(s.substring(sub.length()));

In the substring method, I have only used the starting index to print the substring where I will be getting a string without the prefix. The output looks like this:

Speedy

Exception Handling with a substring

Exceptions are raised with the substring when:

  • Starting index is less than zero
  • Starting index is greater than the ending index
  • The ending index is greater than the total length of the string

The name of the Exception is IndexOutOfBoundException.

Leave a Reply

Your email address will not be published. Required fields are marked *