且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-11-09 23:39:22

将数组保存在局部变量中,并使用数组的 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