Get the substring after the first occurrence of a separator in Java


We have the following string with a separator.

String str = "Tom-Hanks";

We want the substring after the first occurrence of the separator i.e.

Hanks

For that, first you need to get the index of the separator and then using the substring() method get, the substring after the separator.

String separator ="-";
int sepPos = str.indexOf(separator);
System.out.println("Substring after separator = "+str.substring(sepPos + separator.length()));

The following is an example.

Example

 Live Demo

public class Demo {
   public static void main(String[] args) {
      String str = "Tom-Hanks";
      String separator ="-";
      int sepPos = str.indexOf(separator);
      if (sepPos == -1) {
         System.out.println("");
      }
      System.out.println("Substring after separator = "+str.substring(sepPos +       separator.length()));
   }
}

Output

Substring after separator = Hanks

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 27-Jun-2020

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements