我有一个字符串:
/abc/def/ghfj.doc
我想从中提取ghfj.doc,即在最后一个/之后的子字符串,或从右边的第一个/。
有人能帮帮忙吗?
我有一个字符串:
/abc/def/ghfj.doc
我想从中提取ghfj.doc,即在最后一个/之后的子字符串,或从右边的第一个/。
有人能帮帮忙吗?
当前回答
我认为如果我们直接使用分裂函数会更好
String toSplit = "/abc/def/ghfj.doc";
String result[] = toSplit.split("/");
String returnValue = result[result.length - 1]; //equals "ghfj.doc"
其他回答
用番石榴这样做:
String id="/abc/def/ghfj.doc";
String valIfSplitIsEmpty="";
return Iterables.getLast(Splitter.on("/").split(id),valIfSplitIsEmpty);
最终配置并使用Splitter
Splitter.on("/")
.trimResults()
.omitEmptyStrings()
...
还可以看看这篇关于番石榴分离器的文章和这篇关于番石榴迭代的文章
这也可以获取文件名
import java.nio.file.Paths;
import java.nio.file.Path;
Path path = Paths.get("/abc/def/ghfj.doc");
System.out.println(path.getFileName().toString());
是否打印ghfj.doc
一个非常简单的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];
String example = "/abc/def/ghfj.doc";
System.out.println(example.substring(example.lastIndexOf("/") + 1));
在Kotlin中,您可以使用substringAfterLast,指定分隔符。
val string = "/abc/def/ghfj.doc"
val result = url.substringAfterLast("/")
println(result)
// It will show ghfj.doc
医生说:
返回分隔符最后出现后的子字符串。如果字符串不包含分隔符,则返回默认为原始字符串的missingDelimiterValue。