How to get the substring before the last occurrence of a separator in a string with Java

1 Answer

0 votes
public class MyClass {
    public static void main(String args[]) {
      String str = "java-c-c++-python-c#-php";
      String separator ="-";
      
      int separator_pos = str.lastIndexOf(separator);
      
      if (separator_pos == -1) {
         System.out.println("");
      }
      
      System.out.println(str.substring(0, separator_pos));
    }
}




/*
run:

java-c-c++-python-c#

*/

 



answered Sep 7, 2022 by avibootz
...