Java:分割后获取最后一个元素 [英] Java: Get last element after split

查看:1168
本文介绍了Java:分割后获取最后一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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];

这篇关于Java:分割后获取最后一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆