Reputation: 107
What is an efficient way to get number 17 from the following path?
/contacts/lookup/1217x31-2BN8629/17/data
It works with
substring(path.lastIndexOf('/') - 2, path.lastIndexOf('/'))
But then it is hardcoded for a number 10-99, and if a number is for example 3, it will return /3 etc.
Upvotes: 1
Views: 325
Reputation: 12234
First: perform each operation only once. Use a local variable to store data that you will need a second time.
Second: you can look for the next '/' character once you have found the last one.
Eg:
final int lastSlashIndex = path.lastIndexOf('/');
final int nextToLastSlashIndex = path.lastIndexOf('/', lastSlashIndex-1);
path.substring(nextToLastSlashIndex+1, lastSlashIndex);
Upvotes: 2
Reputation: 312146
The easiest, IMHO, would be to split the string according to the /
character, and take the before-last element:
String[] parts = str.split("/");
String result = parts[parts.length - 2];
Upvotes: 3