253

I have a string:

/abc/def/ghfj.doc

I would like to extract ghfj.doc from this, i.e. the substring after the last /, or first / from right.

Could someone please provide some help?

Sébastien Le Callonnec
  • 26,254
  • 8
  • 67
  • 80
Sunny
  • 7,444
  • 22
  • 63
  • 104
  • 53
    look, i understand the value of searching for the answer yourself before asking questions, but the fact of the matter is this question made my search much easier.. exactly what I wanted after the first hit. Quicker than consulting javadocs. It's good that this question is here. Why the downvotes? – Eric Sep 18 '13 at 16:48
  • 3
    Although this is somewhat different from your original question: In your example org.apache.commons.io.FilenameUtils.getBaseName is much more reliable than doing your own string operations. – Till Schäfer Nov 26 '15 at 10:51
  • 5
    @Eric I completely agree with your comment as this was the first Google result for my question and the accepted answer is exactly what I needed to use. – thonnor Jun 20 '16 at 14:44

10 Answers10

396
String example = "/abc/def/ghfj.doc";
System.out.println(example.substring(example.lastIndexOf("/") + 1));
Lars Flieger
  • 2,421
  • 1
  • 12
  • 34
Sébastien Le Callonnec
  • 26,254
  • 8
  • 67
  • 80
53

A very simple implementation with String.split():

String path = "/abc/def/ghfj.doc";
// Split path into segments
String segments[] = path.split("/");
// Grab the last segment
String document = segments[segments.length - 1];
Veger
  • 37,240
  • 11
  • 105
  • 116
44

what have you tried? it's very simple:

String s = "/abc/def/ghfj.doc";
s.substring(s.lastIndexOf("/") + 1)
vishal_aim
  • 7,636
  • 1
  • 20
  • 23
35

Another way is to use this.

String path = "/abc/def/ghfj.doc"
String fileName = StringUtils.substringAfterLast(path, "/");

If you pass null to this method it will return null. If there is no match with separator it will return empty string.

Priyantha
  • 4,839
  • 6
  • 26
  • 46
Alex Green
  • 488
  • 4
  • 8
  • 1
    Finally something really handy, didn't know about this method. I hate to hassle with substring + indexof + 1 - 2 +3 whatsoever. This is much cleaner :) – BAERUS Feb 06 '18 at 08:05
  • If you want to use this method on Android, you have to import `StringUtils` library, this answer shows hot to do it: https://stackoverflow.com/a/33935645/2966583 – stramin Jan 31 '20 at 12:11
12

You can use Apache commons:

For substring after last occurrence use this method.

And for substring after first occurrence equivalent method is here.

Priyantha
  • 4,839
  • 6
  • 26
  • 46
Michal Przysucha
  • 1,021
  • 11
  • 13
8

This can also get the filename

import java.nio.file.Paths;
import java.nio.file.Path;
Path path = Paths.get("/abc/def/ghfj.doc");
System.out.println(path.getFileName().toString());

Will print ghfj.doc

pushya
  • 4,338
  • 10
  • 45
  • 54
6

In Kotlin you can use substringAfterLast, specifying a delimiter.

val string = "/abc/def/ghfj.doc"
val result = url.substringAfterLast("/")
println(result)
// It will show ghfj.doc

From the doc:

Returns a substring after the last occurrence of delimiter. If the string does not contain the delimiter, returns missingDelimiterValue which defaults to the original string.

Filipe Brito
  • 5,329
  • 5
  • 32
  • 42
4

With Guava do this:

String id="/abc/def/ghfj.doc";
String valIfSplitIsEmpty="";
return Iterables.getLast(Splitter.on("/").split(id),valIfSplitIsEmpty);

Eventually configure the Splitter and use

Splitter.on("/")
.trimResults()
.omitEmptyStrings()
...

Also take a look into this article on guava Splitter and this article on guava Iterables

jschnasse
  • 8,526
  • 6
  • 32
  • 72
  • Note that this solution if not very effective due to creation of extra objects for every split point. – Vadzim Oct 21 '20 at 19:01
  • 1
    @Vadzim Correct. This should be considered. Also see this discussion: https://stackoverflow.com/questions/42584477/should-guava-splitters-joiners-be-created-each-time-they-are-used – jschnasse Nov 12 '20 at 10:14
0

I think that would be better if we use directly the split function

String toSplit = "/abc/def/ghfj.doc";

String result[] = toSplit.split("/");

String returnValue = result[result.length - 1]; //equals "ghfj.doc"
Luís Cruz
  • 14,780
  • 16
  • 68
  • 100
  • this code will throw an error if the separator is not found. – Patrick Parker Jul 24 '18 at 20:58
  • @PatrickParker Why have you commented everywhere that it will throw an error if the separator is not found. If you are doing it for knowledge purposes than okay, but I just think it's a bit too much maybe... – Gaurav Mall Jul 06 '19 at 14:51
  • @GauravMall I am helping people to improve their answers, to write better code, and for those who are visiting to help them avoid pitfalls and build understanding of the code before they paste it somewhere. I will gladly remove my comment once the answer is improved. Also, writing it in two places is hardly "everywhere". Finally, the comment section is not for meta discussion. – Patrick Parker Jul 17 '19 at 15:26
0

java android

in my case

I want to change from

~/propic/........png

anything after /propic/ doesn't matter what before it

........png

finally, I found the code in Class StringUtils

this is the code

     public static String substringAfter(final String str, final String separator) {
         if (isEmpty(str)) {
             return str;
         }
         if (separator == null) {
             return "";
         }
         final int pos = str.indexOf(separator);
         if (pos == 0) {
             return str;
         }
         return str.substring(pos + separator.length());
     }
Hassan Badawi
  • 302
  • 1
  • 10
  • `substringAfter("abc", "a") == "abc"` this doesn't work as original substring after – R A Feb 23 '23 at 11:31