Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - second last occurrence of char in string

Tags:

java

string

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.

like image 437
antikbd Avatar asked Dec 02 '22 10:12

antikbd


1 Answers

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

like image 136
walen Avatar answered Jan 18 '23 23:01

walen