Well, many down votes but I’ll add a solution
the most efficient way to do that is using java.lang.String#lastIndexOf, which returns the index within this string of the last occurrence of the specified character, searching backwards
lastIndexOf will return -1 if dash does not exist
String str = "first-second-third";
int lastIndexOf = str.lastIndexOf('-');
System.out.println(lastIndexOf);
System.out.println(str.substring(0, lastIndexOf)); // 0 represent to cut from the beginning of the string
output:
12
first-second
4
solved Java – Split string with multiple dash