activelearner
activelearner

Reputation: 7795

Java - Get substring from 2nd last occurrence of a character in string

My input: "professions/medical/doctor/"

My desired output: "doctor"

I have the following solution but it is not a one-liner:

String v = "professions/medical/doctor/";
String v1 = v.substring(0, v.length() - 1);
String v2 = v1.substring(v1.lastIndexOf("/")+1, v1.length());
System.out.println(v2);

How can I achieve the same in a one-liner?

Upvotes: 1

Views: 2337

Answers (2)

iluxa
iluxa

Reputation: 6969

Use lastIndexOf(str, fromIndex) variant:

String v2 = v.substring(v.lastIndexOf('/', v.length() - 2) + 1, v.length() - 1);

Upvotes: 1

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522626

I would probably use String#split here (requiring either a one or two line solution):

String v = "professions/medical/doctor/";
String[] parts = v.split("/");
String v2 = parts[parts.length-1];
System.out.println(v2);

If you know that you want the third component, then you may just use:

System.out.println(v.split("/")[2]);

For a true one-liner, String#replaceAll might work:

String v = "professions/medical/doctor/";
String v2 = v.replaceAll(".*/([^/]+).*", "$1");
System.out.println(v2);

Upvotes: 4

Related Questions