我正在使用字符串拆分方法,我想要最后一个元素。数组的大小可以更改。
示例:
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?我不知道运行时数组的大小:(
发布于 2009-07-25 12:03:18
将数组保存在局部变量中,并使用数组的length字段查找其长度。以0为基数减去1:
String[] bits = one.split("-");
String lastOne = bits[bits.length-1];注意:如果原始字符串仅由分隔符组成,例如"-"或"---",则bits.length将为0,这将抛出ArrayIndexOutOfBoundsException。示例:https://onlinegdb.com/r1M-TJkZ8
发布于 2009-07-25 12:05:33
或者,您可以对字符串使用lastIndexOf()方法
String last = string.substring(string.lastIndexOf('-') + 1);发布于 2017-05-02 17:02:56
您可以在Apache Commons中使用StringUtils类:
StringUtils.substringAfterLast(one, "-");https://stackoverflow.com/questions/1181969
复制相似问题