Java:拆分后获取最后一个元素 [英] Java: Get last element after split
问题描述
我正在使用字符串拆分方法,并且我想要最后一个元素.Array 的大小可以改变.
I am using the String split method and I want to have the last element. The size of the Array can change.
示例:
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 :(
推荐答案
将数组保存在局部变量中,并使用数组的 length
字段来查找其长度.减去一个以说明它是基于 0 的:
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];
Caveat emptor:如果原始字符串仅由分隔符组成,例如 "-"
或 "---"
, bits.length
将为 0,这将引发 ArrayIndexOutOfBoundsException.示例:https://onlinegdb.com/r1M-TJkZ8
Caveat emptor: if the original string is composed of only the separator, for example "-"
or "---"
, bits.length
will be 0 and this will throw an ArrayIndexOutOfBoundsException. Example: https://onlinegdb.com/r1M-TJkZ8
这篇关于Java:拆分后获取最后一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!