tags:

views:

1298

answers:

4

Hi there
i am using the String split method and i want to have the last element. The size of the Array can change.

examples :

 String one =  "Düsseldorf - Zentrum - Günnewig Uebachs"
 String two =  "Düsseldorf - Madison"

i want to split this and get the last item :

lastone = one.split("-")[here the last item] <- how?
lasttwo = one.split("-")[here the last item] <- how?

i don't know the sizes of the arrays at rumtime :(

+7  A: 

Save the array in a local variable and use the array's length field to find its length. Subtract one to account for it being 0-based:

String[] bits = one.split("-");
String lastOne = bits[bits.length-1];
Jon Skeet
this is what i was looking for : thanks :)
n00ki3
Just be aware that in the case where the input string is empty, the second statement will throw an "index out of bounds" exception.
Stephen C
+1  A: 

You mean you don't know the sizes of the arrays at compile-time? At run-time they could be found by the value of lastone.length and lastwo.length .

Sean A.O. Harney
+4  A: 

Or you could use lastIndexOf() method on String

String last = string.substring(string.lastIndexOf('-') + 1);
dotsid
i think this solution takes less resources.
ufk
+7  A: 

using a simple, yet generic, helper method like this:

public static <T> T last(T[] array) {
    return array[array.length - 1];
}

you can rewrite:

lastone = one.split("-")[..];

as:

lastone = last(one.split("-"));
dfa
Very elegant. :) The possibilities of generic static methods are amazing.
Emil H
One thing you should do is protect last() method against empty arrays or you could get IndexOutOfBoundsException.
dotsid
@dotsid, On the other hand it might be better to throw an ArrayIndexOutOfBoundsException rather than return null here, since you'll catch the error where it occurs rather when it causes the problem.
Emil H
@dotsid, I would leave this responsibility to the caller, hiding runtime exceptions is dangerous
dfa