给定一个包含下划线字符的字符串,如何将其分割成围绕最后一个下划线字符的两个子字符串?
例如. "a_b_c" => ["a_b", "_c"]
String
上使用lastIndexOf
,它将返回最后一次出现一串字符的索引位置。
你可以在String
上使用lastIndexOf
,它将返回最后一次出现一串字符的索引位置。
String thing = "132131_12313_1321_312";
int index = thing.lastIndexOf("_");
String yourCuttedString = thing.substring(0, index);
如果在字符串中没有找到该项,则返回-1
。
你可以使用String#lastIndexOf(String str)
方法, 试试看:
int lastIndexOf = str.lastIndexOf("_");
String substring1 = str.substring(0, lastIndexOf);
String substring2 = str.substring(lastIndexOf+1, str.length());
试一下这个
String[] a = s.split("_(?!.*_)");
String code = "123_456_789";
String subString = code.subString(code.lastIndexOf("_"));
int
参数的split
方法。 - user432
str.substring(lastIndexOf+1, str.length())
可以直接写作str.substring(lastIndexOf+1)
。 - lpratlong