Java: Get last element after split

n00ki3 picture n00ki3 · Jul 25, 2009 · Viewed 241.5k times · Source

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

Example:

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

I want to split the above Strings and get the last item:

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

I don't know the sizes of the arrays at runtime :(

Answer

Denis Bazhenov picture Denis Bazhenov · Jul 25, 2009

Or you could use lastIndexOf() method on String

String last = string.substring(string.lastIndexOf('-') + 1);