1

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?

activelearner
  • 7,055
  • 20
  • 53
  • 94
  • You can use a regex to achieve the same. Something like \/\w+\/$ would give you the match. – Leni Oct 31 '19 at 02:16

2 Answers2

3

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);
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
1

Use lastIndexOf(str, fromIndex) variant:

String v2 = v.substring(v.lastIndexOf('/', v.length() - 2) + 1, v.length() - 1);
iluxa
  • 6,941
  • 18
  • 36