Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any simpler way to get the last element of a Java array? [duplicate]

Tags:

java

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.

like image 781
Terry Li Avatar asked Mar 09 '13 23:03

Terry Li


People also ask

How do you find duplicate elements in an array Java?

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.

Which expression can be used to access the last element of an array in Java?

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.


2 Answers

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.

like image 145
Makoto Avatar answered Nov 13 '22 14:11

Makoto


Another way to get the last token/word

String lastToken = sentance.replaceAll(".* ", "");
like image 25
Peter Lawrey Avatar answered Nov 13 '22 14:11

Peter Lawrey