Java 在某个字符的最后一次出现时拆分字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20904922/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Split string on the last occurrence of some character
提问by sirvon
I'm basically trying to split a string on the last period to capture the file extension. But sometimesthe file doesn't have anyextension, so I'm anticipating that.
我基本上是试图在最后一个时期拆分一个字符串来捕获文件扩展名。但有时文件没有任何扩展名,所以我很期待。
But the problem is that some file names have periods before the end like so...
但问题是某些文件名在末尾有句点,就像这样......
/mnt/sdcard/OG Ron C, Chopstars & Drake - Choppin Ain't The Same-2013-MIXFIEND/02 Drake - Connect (Feat. Fat Pat) (Chopped Not Slopped).mp3
So when that string comes up it chops it at "02 Drake - Connect (Feat."
因此,当该字符串出现时,它会在“02 Drake - Connect (Feat.”) 处将其斩断。
This is what I've been using...
这是我一直在用的...
String filePath = intent.getStringExtra(ARG_FILE_PATH);
String fileType = filePath.substring(filePath.length() - 4);
String FileExt = null;
try {
StringTokenizer tokens = new StringTokenizer(filePath, ".");
String first = tokens.nextToken();
FileExt = tokens.nextToken();
}
catch(NoSuchElementException e) {
customToast("the scene you chose, has no extension :(");
}
System.out.println("EXT " + FileExt);
File fileToUpload = new File(filePath);
How do I split the string at the file extension but also be able to handle and alert when the file has no extension.
如何在文件扩展名处拆分字符串,但也能够在文件没有扩展名时进行处理和提醒。
采纳答案by user1537366
It might be easier to just assume that files which end with a dot followed by alphanumeric characters have extensions.
假设以点结尾后跟字母数字字符的文件具有扩展名可能更容易。
int p=filePath.lastIndexOf(".");
String e=filePath.substring(p+1);
if( p==-1 || !e.matches("\w+") ){/* file has no extension */}
else{ /* file has extension e */ }
See the Java docsfor regular expression patterns. Remember to escape the backslash because the pattern string needs the backslash.
有关正则表达式模式,请参阅Java 文档。记住要转义反斜杠,因为模式字符串需要反斜杠。
回答by Juned Ahsan
How about splitting the filPath using the period as separator. And taking the last item in that array to get the extension:
如何使用句点作为分隔符拆分 filPath。并获取该数组中的最后一项以获取扩展名:
String fileTypeArray[] = filePath.split(",");
String fileType = "";
if(fileTypeArray != null && fileTypeArray.length > 0) {
fileType = fileTypeArray[fileTypeArray.length - 1];
}
回答by Evgeniy Dorofeev
You can try this
你可以试试这个
int i = s.lastIndexOf(c);
String[] a = {s.substring(0, i), s.substring(i)};
回答by Kei Minagawa
Is this Java? If so, why don't you use "java.io.File.getName".
这是爪哇吗?如果是这样,为什么不使用“java.io.File.getName”。
For example:
例如:
File f = new File("/aaa/bbb/ccc.txt");
System.out.println(f.getName());
Out:
出去:
ccc.txt