If you are doing this just once, then Peter Lawrey's solution is shorter, though IMO it is harder to understand than the original version.
If you are doing this in multiple places then the following is better:
public String lastToken(String str, String separatorRegex) {
String tokens[] = str.split(separatorRegex);
return tokens[tokens.length - 1];
}
and then
String lastToken = lastToken(sentence, " ");
... which is more elegant than any clever hack ... IMO.
My more general point is that time spent trying to make a single line of code shorter is probably time wasted ... or worse:
- From the perspective of SOMEONE ELSE reading your code, one lines versus two lines is irrelevant.
- If the clever hack that makes the line shorter is obscure, then you have actually done a BAD THING by using it ... from the perspective of the next guy who reads / maintains your code.
- If the clever hack is less efficient than the inelegant version, you may have introduced a performance issue.
But if you are repeating that line of code (or similar) in lots of places, then the best solution is to use procedural abstraction. Write a static or instance method ... once ... and call it multiple times.