How to trim String from the back in Java?

Take a look at the documentation for the String class here.

You can use the substring and lastIndexOf methods:

String str = "ahfckhs_aidewiofh_asa_rrresf";
String trimmed = str.substring(0, str.lastIndexOf("_"));
System.out.println(trimmed);

Output:

ahfckhs_aidewiofh_asa

Leave a Comment