Java: Getting a substring from a string starting after a particular character

I have a string:

/abc/def/ghfj.doc

I would like to extract ghfj.doc from this, i.e. the substring after the last /, or first / from right.

Could someone please provide some help?


Solution 1:

String example = "/abc/def/ghfj.doc";
System.out.println(example.substring(example.lastIndexOf("/") + 1));

Solution 2:

A very simple implementation with String.split():

String path = "/abc/def/ghfj.doc";
// Split path into segments
String segments[] = path.split("/");
// Grab the last segment
String document = segments[segments.length - 1];

Solution 3:

what have you tried? it's very simple:

String s = "/abc/def/ghfj.doc";
s.substring(s.lastIndexOf("/") + 1)