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?

1
  • You can use a regex to achieve the same. Something like \/\w+\/$ would give you the match. Commented Oct 31, 2019 at 2:16

2 Answers 2

4

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);
Sign up to request clarification or add additional context in comments.

3 Comments

I like the split technique here. Split into segments and pull out which one you want.
I like split too. Banana split - more so.
@ScaryWombat Now just stop that! You're making me hungry.
1

Use lastIndexOf(str, fromIndex) variant:

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

2 Comments

I get this error: java.lang.StringIndexOutOfBoundsException: String index out of range: -1 @iluxa
My bad, misunderstood the fromIndex. Updated the answer, try that

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.