菜鸟笔记
提升您的技术认知

Java:获取分割后的最后一个元素

Java:获取分割后的最后一个元素

我正在使用string拆分方法,我想要最后一个元素。 数组的大小可以改变。

例:

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

我想分割上面的string,并得到最后一个项目:

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

我不知道在运行时数组的大小:(

将数组保存在局部variables中,并使用数组的length字段来查找其长度。 减去一个来解释它是基于0的:

 String[] bits = one.split("-"); String lastOne = bits[bits.length-1]; 

或者你可以在String上使用lastIndexOf()方法

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

使用一个简单但通用的辅助方法,如下所示:

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

你可以重写:

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

如:

 lastone = last(one.split("-")); 

您可以使用Apache Commons中的StringUtils类:

 StringUtils.substringAfterLast(one, "-"); 
 String str = "www.anywebsite.com/folder/subfolder/directory"; int index = str.lastIndexOf('/'); String lastString = str.substring(index +1); 

现在lastString的值是"directory"

番石榴 :

 final Splitter splitter = Splitter.on("-").trimResults(); assertEquals("Günnewig Uebachs", Iterables.getLast(splitter.split(one))); assertEquals("Madison", Iterables.getLast(splitter.split(two))); 

SplitterIterables

由于他要求所有在同一行使用拆分,所以我build议这样做:

 lastone = one.split("-")[(one.split("-")).length -1] 

我总是尽量避免定义新的variables,我觉得这是一个非常好的做法

你的意思是在编译时你不知道数组的大小? 在运行时,可以通过lastone.lengthlastwo.length的值来find它们。