Get the substring before the last occurrence of a separator in Java

Java 8Object Oriented ProgrammingProgramming

We have the following string with a separator.

String str = "David-Warner";

We want the substring before the last occurrence of a separator. Use the lastIndexOf() method.

For that, you need to get the index of the separator using indexOf()

String separator ="-";
int sepPos = str.lastIndexOf(separator);
System.out.println("Substring before last separator = "+str.substring(0,sepPos));

The following is an example.

Example

 Live Demo

public class Demo {
   public static void main(String[] args) {
      String str = "David-Warner";
      String separator ="-";
      int sepPos = str.lastIndexOf(separator);
      if (sepPos == -1) {
         System.out.println("");
      }
      System.out.println("Substring before last separator = "+str.substring(0,sepPos));
   }
}

Output

Substring before last separator = David
raja
Published on 17-Dec-2018 11:14:21
Advertisements