7

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.

5
  • 2
    What exactly doesn't work? We need more info. Commented Jan 11, 2019 at 6:59
  • It seems to scan from the beginning, not the end. So the output comes just /. Commented Jan 11, 2019 at 7:01
  • 1
    As its stated in the docs. The method only return the index value and not a string Commented Jan 11, 2019 at 7:02
  • ^ That was a typo Commented Jan 11, 2019 at 7:04
  • 1
    Remember that with the substring(start , end) makes a substring from the start to, but not including' the end index. So if you want the last / in your output string, just add +1 to your end Commented Jan 11, 2019 at 7:08

10 Answers 10

8

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

Sign up to request clarification or add additional context in comments.

1 Comment

Definitely will be saving this. Very flexible.
5

This works, given path length >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);

Comments

3

The lastIndexOf method's second parameter specifies the maximum index upto where the method should search the string. This means, that in your case

path.lastIndexOf("/", 1)

returns the first index of "/" whose index is smaller than 1.

1 Comment

Yep got the problem now. Thanks for the help.
3

First of all, lastIndexOf will return an index, not a string. It also searches backwards from the specified index 1, so it will only look at everything before and including the character at index 1. This means that it only checks t and h. Expectedly, it finds nothing and returns -1.

You should just omit the second argument if you want to search the whole string.

In addition, to achieve your desired output string (I assume you want the last path component removed?), you can use replaceAll with a regex:

String output = path.replaceAll("[^/]+/$", "");

1 Comment

Thanks for the explanation. I think you're right - regex is the best way to handle this. BTW, I didn't downvote you.
2

Try - 1 approach:

int j = path.lastIndexOf("/");
int i = path.lastIndexOf("/", j - 1);      // the 2nd last index from the last index

String output = path.substring(0, i + 1);  // inclusive

Comments

1

Using Apache Commons IO

String output = org.apache.commons.io.FilenameUtils.getPath(path);

Not using Apache

public static String removeLastPart(String str) {
    int pos = str.length() - 1;

    while (str.charAt(pos) != '/' || pos + 1 == str.length()) {
        pos--;
    }

    return str.substring(0, pos + 1);
}

Comments

1

If you are dealing with paths and files why not use the built in classes? Something like below seems to me easier than string manipulation:

Path path = Paths.get("the/quick/brown/fox/jumped/over/the/lazy/dog/");
System.out.println(path.getParent());
// prints: the\quick\brown\fox\jumped\over\the\lazy
System.out.println(path.getParent().getParent());
// prints: the\quick\brown\fox\jumped\over\the

Comments

1

For example, String key = "aaa/bbb/ccc/ddd" ;

and i need my result string as "ccc/ddd". which is, sub-string of second last index of "/", The following code helps ::

    String key="aaa/bbb/ccc/ddd";
    key=key.substring(key.substring(0, key.lastIndexOf("/")).lastIndexOf("/")+1);

The final value of key will be "ccc/ddd".

Comments

1

Here's an use case:

        String url = "http://localhost:4000/app/getPTVars";
        int secondLastIndexOf = url.substring(0, url.lastIndexOf('/')).lastIndexOf('/');
        System.out.println(secondLastIndexOf);
        System.out.println(url.substring(secondLastIndexOf, url.length()));

and the output:

21
/app/getPTVars

Comments

0

String path = "the/quick/brown/fox/jumped/over/the/lazy/dog/";

String output = path.substring(0, path.lastIndexOf("/",path.lastIndexOf("/")-1)+1);

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.