问题
我正在使用String split方法,我想拥有最后一个元素。数组的大小可以改变。
示例:
String one = "Düsseldorf - Zentrum - Günnewig Uebachs"
String two = "Düsseldorf - Madison"
我想拆分上面的字符串并得到最后一项:
lastone = one.split("-")[here the last item] // <- how?
lasttwo = two.split("-")[here the last item] // <- how?
我不知道运行时数组的大小:(
#1 热门回答(200 赞)
或者你可以在String上使用lastIndexOf()
方法
String last = string.substring(string.lastIndexOf('-') + 1);
#2 热门回答(144 赞)
将数组保存在局部变量中,并使用数组的length
字段查找其长度。减去1以说明它是基于0的:
String[] bits = one.split("-");
String lastOne = bits[bits.length-1];
#3 热门回答(22 赞)
使用这样一个简单但通用的辅助方法:
public static <T> T last(T[] array) {
return array[array.length - 1];
}
你可以改写:
lastone = one.split("-")[..];
如:
lastone = last(one.split("-"));