在我上面的问题的答案中,return id.substring(0, lastDot - 1);
在这一行lastDot
遇到了问题。
如果我的 id 为 1.1,则上行 lastDot
值为 1
子字符串将变为 ""
。
如何避免这个问题。
private String getParentId(String id) {
int lastDot = id.lastIndexOf(".");
if (lastDot == -1) {
return null;
}
return id.substring(0, lastDot - 1);
}
最佳答案
检查java文档:https://docs.oracle.com/javase/8/docs/api/java/lang/String.html
第二个参数是从第一个参数开始的字符串长度,因此如果始终从索引 0 开始,则不需要减 1
return id.substring(0, lastDot);
更通用的方法是始终减去第一个参数
int offset = 0;
return id.substring(offset, lastDot-offset);
关于java - 子字符串不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45650842/