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


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

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 27-Jun-2020

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements