Reputation: 378
In my above question's answer return id.substring(0, lastDot - 1);
in this line lastDot
is getting problem.
If I have the id 1.1 the in the above line lastDot
value is 1
the substring is getting ""
.
How can I avoid the problem.
private String getParentId(String id) {
int lastDot = id.lastIndexOf(".");
if (lastDot == -1) {
return null;
}
return id.substring(0, lastDot - 1);
}
Upvotes: 0
Views: 94
Reputation: 6574
Check the java docs: https://docs.oracle.com/javase/8/docs/api/java/lang/String.html
The second parameter is the length of the string starting from the first parameter, so if you are always starting with index 0 , you do not need to subtract 1
return id.substring(0, lastDot);
A more general approach would be to always subtract the first parameter
int offset = 0;
return id.substring(offset, lastDot-offset);
Upvotes: 4
Reputation: 121068
return id.substring(0, lastDot);
is what you meant probably. But think of the case when your id would be 1.2.3
what would like to return in this case? 1.2
or 2
or 1
. At the moment your function will return 1.2
at it might be correct - but that depends on your needs.
Upvotes: 1