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

Java 8Object Oriented ProgrammingProgramming

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
raja
Published on 17-Dec-2018 11:08:15
Advertisements