我有一个字符串:
/abc/def/ghfj.doc
我想从中提取ghfj.doc,即在最后一个/之后的子字符串,或从右开始的第一个/。
ghfj.doc
/
有人能帮帮忙吗?
String.split()的一个非常简单的实现:
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));
你试过什么? 这很简单:
String s = "/abc/def/ghfj.doc"; s.substring(s.lastIndexOf("/") + 1)
我认为如果我们直接使用分裂函数会更好
String toSplit = "/abc/def/ghfj.doc"; String result[] = toSplit.split("/"); String returnValue = result[result.length - 1]; //equals "ghfj.doc"
你可以使用Apache commons:
对于上次出现后的子字符串,使用这方法。
而对于第一次出现后的子字符串,等效方法为在这里。
这也可以获取文件名
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 path = "/abc/def/ghfj.doc" String fileName = StringUtils.substringAfterLast(path, "/");
如果你将null传递给这个方法,它将返回null。如果与分隔符不匹配,则返回空字符串。
在Kotlin中,你可以使用substringAfterLast来指定分隔符。
substringAfterLast
val string = "/abc/def/ghfj.doc" val result = url.substringAfterLast("/") println(result) // It will show ghfj.doc
从医生:
返回分隔符最后出现后的子字符串。如果字符串不包含分隔符,则返回默认为原始字符串的missingDelimiterValue。
使用番石榴执行以下操作:
String id="/abc/def/ghfj.doc"; String valIfSplitIsEmpty=""; return Iterables.getLast(Splitter.on("/").split(id),valIfSplitIsEmpty);
最终配置Splitter并使用
Splitter
Splitter.on("/") .trimResults() .omitEmptyStrings() ...
再看一下这篇文章关于番石榴分离器和这篇关于番石榴迭代的文章
java安卓
对我来说
我想从
~ / propic /……png
/ propic /之后的任何内容都与它之前的内容无关
……png
最后,我在类的stringutil中找到了代码
这就是代码
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()); }