what have you tried? it's very simple:
String s = "/abc/def/ghfj.doc";
s.substring(s.lastIndexOf("/") + 1)
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
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.
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.
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
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());
}
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];
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"
Source: Stackoverflow.com