Issue
How can I retrieve the nth value of a char-delimited string in one line?
If the string was '.' delimited, and I wanted to take a string a.b.c and retrieve c in Python, I would simply do:
'a.b.c'.split('.')[-1].
Seemingly, the equivalent in Java is:
String beforeSplit = "a.b.c";
String[] parts = beforeSplit.split("\\.");
String afterSplit = parts[parts.length - 1];
Is there a way to consolidate this into a one-line expression without using intermediate variables/strings to store the parts? e.g.:
String consolidated = 'a.b.c'.split("\\.")[this.length -1];
After doing some experimenting, it doesn't seem like this is an operable way to refer to the preceeding result's return value, in one line.
I suspect this would result in an ugly closure of some form but maybe there's an easier method that I am not aware of?
Solution
Spontaneously I can't think of an elegant one except replacing using regex:
String lastPart = "a.b.c".replaceAll("^.*?([^\\.]*)$","$1");
or using lastindexOf
String lastPart = "a.b.c".substring("a.b.c".lastIndexOf('.') + 1);
Answered By - Eritrean
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.