Suppose I've the string
String path = "the/quick/brown/fox/jumped/over/the/lazy/dog/";
I would like the following output
String output = "the/quick/brown/fox/jumped/over/the/lazy/";
I was thinking the following would do
output = path.substring(0, path.lastIndexOf("/", 1));
given how the doc says
Returns the index of the first (last) occurrence of the specified character, searching forward (backward) from the specified index.
but that doesn't seem to work.
Any help would be appreciated.
It seems like every single answer is assuming that you already know the input string and the exact position of the last occurrence of "/"
in it, when that is usually not the case...
Here's a more general method to obtain the nth-last (second-last, third-last, etc.) occurrence of a character inside a string:
static int nthLastIndexOf(int nth, String ch, String string) {
if (nth <= 0) return string.length();
return nthLastIndexOf(--nth, ch, string.substring(0, string.lastIndexOf(ch)));
}
Usage:
String s = "the/quick/brown/fox/jumped/over/the/lazy/dog/";
System.out.println(s.substring(0, nthLastIndexOf(2, "/", s)+1)); // substring up to 2nd last included
System.out.println(s.substring(0, nthLastIndexOf(3, "/", s)+1)); // up to 3rd last inc.
System.out.println(s.substring(0, nthLastIndexOf(7, "/", s)+1)); // 7th last inc.
System.out.println(s.substring(0, nthLastIndexOf(2, "/", s))); // 2nd last, char itself excluded
Output:
the/quick/brown/fox/jumped/over/the/lazy/
the/quick/brown/fox/jumped/over/the/
the/quick/brown/
the/quick/brown/fox/jumped/over/the/lazy
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With