Objective-C:从路径字符串中提取文件名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1098957/
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
Objective-C: Extract filename from path string
提问by Anton
When I have NSStringwith /Users/user/Projects/thefile.extI want to extract thefilewith Objective-C methods.
当我有NSString跟/Users/user/Projects/thefile.ext我要提取thefile使用Objective-C的方法。
What is the easiest way to do that?
最简单的方法是什么?
回答by Peter
Taken from the NSString reference, you can use :
取自NSString 参考,您可以使用:
NSString *theFileName = [[string lastPathComponent] stringByDeletingPathExtension];
The lastPathComponentcall will return thefile.ext, and the stringByDeletingPathExtensionwill remove the extension suffix from the end.
该lastPathComponent调用将返回thefile.ext,而stringByDeletingPathExtension将最后删除的扩展名后缀。
回答by Marc Charbonneau
If you're displaying a user-readable file name, you do notwant to use lastPathComponent. Instead, pass the full path to NSFileManager's displayNameAtPath:method. This basically does does the same thing, only it correctly localizes the file name and removes the extension based on the user's preferences.
如果你显示用户可读的文件名,你不希望使用lastPathComponent。相反,将完整路径传递给 NSFileManager 的displayNameAtPath:方法。这基本上做同样的事情,只是它正确地本地化文件名并根据用户的偏好删除扩展名。
回答by Chris Conover
At the risk of being years late and off topic - and notwithstanding @Marc's excellent insight, in Swift it looks like:
冒着迟到数年和偏离主题的风险 - 尽管@Marc 有出色的洞察力,但在 Swift 中它看起来像:
let basename = NSURL(string: "path/to/file.ext")?.URLByDeletingPathExtension?.lastPathComponent

