Java:拆分后获取最后一个元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1181969/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 00:36:02  来源:igfitidea点击:

Java: Get last element after split

javastringsplit

提问by n00ki3

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

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

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 :(

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

采纳答案by Jon Skeet

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

将数组保存在局部变量中并使用数组的length字段来查找其长度。减去 1 以说明它是基于 0 的:

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

Caveat emptor: if the original string is composed of only the separator, for example "-"or "---", bits.lengthwill be 0 and this will throw an ArrayIndexOutOfBoundsException. Example: https://onlinegdb.com/r1M-TJkZ8

警告 emptor:如果原始字符串仅由分隔符组成,例如"-"or "---"bits.length将为 0,这将抛出 ArrayIndexOutOfBoundsException。示例:https: //onlinegdb.com/r1M-TJkZ8

回答by Sean A.O. Harney

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.lengthand lastwo.length.

你的意思是你在编译时不知道数组的大小?在运行时,他们可以通过价值发现lastone.lengthlastwo.length

回答by Denis Bazhenov

Or you could use lastIndexOf()method on String

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

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

回答by dfa

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("-"));

回答by azerafati

Since he was asking to do it all in the same line using split so i suggest this:

由于他要求使用 split 在同一行中完成所有操作,因此我建议这样做:

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

I always avoid defining new variables as far as I can, and I find it a very good practice

我总是尽量避免定义新变量,我发现这是一个很好的做法

回答by Jawad Zeb

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

Now lastStringhas the value "directory"

现在lastString有了价值"directory"

回答by palacsint

With Guava:

随着番石榴

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

Splitter, Iterables

Splitter, Iterables

回答by Ranosama

You can use the StringUtilsclass in Apache Commons:

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

StringUtils.substringAfterLast(one, "-");

回答by irJvV

I guess you want to do this in i line. It is possible (a bit of juggling though =^)

我猜您想在 i 行中执行此操作。这是可能的(虽然有点杂耍=^)

new StringBuilder(new StringBuilder("Düsseldorf - Zentrum - Günnewig Uebachs").reverse().toString().split(" - ")[0]).reverse()

tadaa, one line -> the result you want (if you split on " - " (space minus space) instead of only "-" (minus) you will loose the annoying space before the partition too =^) so "Günnewig Uebachs" instead of " Günnewig Uebachs" (with a space as first character)

tadaa,一行 -> 你想要的结果(如果你在“ - ”(空格减去空格)而不是仅“ - ”(减去)上拆分,你也会在分区之前失去烦人的空间=^)所以“Günnewig Uebachs”而不是“Günnewig Uebachs”(以空格作为第一个字符)

Nice extra -> no need for extra JAR files in the lib folder so you can keep your application light weight.

不错的额外 -> lib 文件夹中不需要额外的 JAR 文件,因此您可以保持应用程序的轻量级。

回答by Maxim Sidorov

Also you can use java.util.ArrayDeque

你也可以使用 java.util.ArrayDeque

String last = new ArrayDeque<>(Arrays.asList("1-2".split("-"))).getLast();