Java - 字符串中最后一次出现的字符

ant*_*kbd 4 java string

假设我有字符串

String path = "the/quick/brown/fox/jumped/over/the/lazy/dog/";
Run Code Online (Sandbox Code Playgroud)

我想要以下输出

String output = "the/quick/brown/fox/jumped/over/the/lazy/";
Run Code Online (Sandbox Code Playgroud)

我在想以下会做

output = path.substring(0, path.lastIndexOf("/", 1));
Run Code Online (Sandbox Code Playgroud)

鉴于医生怎么说

返回指定字符第一次(最后一次)出现的索引,从指定索引向前(向后)搜索。

但这似乎不起作用。

任何帮助,将不胜感激。

wal*_*len 6

似乎每个答案都假设您已经知道输入字符串以及其中最后一次出现的确切位置,但"/"通常情况并非如此......
这是获得第 n 个最后一个(第二个-last、倒数第三等)字符在字符串中的出现:

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)));
}
Run Code Online (Sandbox Code Playgroud)

用法:

    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
Run Code Online (Sandbox Code Playgroud)

输出:

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/懒惰的

  • 肯定会保存这个。非常灵活。 (2认同)

Idv*_*dva 5

path给定长度 >2 时,这是可行的

final String path = "the/quick/brown/fox/jumped/over/the/lazy/dog/";
final int secondLast = path.length()-2;
final String output = path.substring(0, path.lastIndexOf("/",secondLast)+1);
System.out.println(output);
Run Code Online (Sandbox Code Playgroud)