String sentence = "Any simpler way to get the last element of a Java array?";
String lastToken = sentence.split(" ")[sentence.split(" ").length-1];
I'd like to split the sentence and get the last token. I feel my way of doing it is a little too awkward. Basically, I want the second statement to be shorter. Is that possible?
Edit: What I'm looking for: 1) no need to declare the array separately 2) no need to split the sentence twice. It would be good if there's a method called last
with array. I suspect this is impossible but want to make sure.
One of the most common ways to find duplicates is by using the brute force method, which compares each element of the array to every other element. This solution has the time complexity of O(n^2) and only exists for academic purposes.
The first and last elements are accessed using an index and the first value is accessed using index 0 and the last element can be accessed through length property which has one more value than the highest array index.
You only need to split it once, and take the last element.
String sentence = "Any simpler way to get the last element of a Java array?";
String[] tokens = sentence.split(" ");
String lastToken = tokens[tokens.length-1];
It's awkward, but there's really no other way to do it unless you have foreknowledge of the length of the string.
Another way to get the last token/word
String lastToken = sentance.replaceAll(".* ", "");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With