Objective-C:从路径字符串中提取文件名

Ant*_*ton 251 cocoa objective-c

当我拥有时NSString,/Users/user/Projects/thefile.ext我想thefile用Objective-C方法提取.

最简单的方法是什么?

Pet*_*ter 598

NSString引用中获取,您可以使用:

NSString *theFileName = [[string lastPathComponent] stringByDeletingPathExtension];
Run Code Online (Sandbox Code Playgroud)

lastPathComponent调用将返回thefile.ext,并将stringByDeletingPathExtension从末尾删除扩展名后缀.

  • @TwoDumpling`NSString*myExtension = [myString pathExtension]` (20认同)
  • 我从未听说过`lastPathComponent`.谢谢! (9认同)
  • 另一个解决方案是这个和Marc的答案的组合:`[[[NSFileManager defaultManager] displayNameAtPath:path] stringByDeletingPathExtension]`(使用你想要的任何文件管理器).这可确保文件名已正确本地化,并且已删除扩展名. (6认同)

Mar*_*eau 37

如果你显示用户可读的文件名,你希望使用lastPathComponent.相反,将完整路径传递给NSFileManager的displayNameAtPath:方法.这基本上做了同样的事情,只是它正确地本地化文件名并根据用户的偏好删除扩展名.


Chr*_*ver 5

冒着迟到多年和偏离主题的风险 - 尽管 @Marc 具有出色的洞察力,但在 Swift 中它看起来像:

let basename = NSURL(string: "path/to/file.ext")?.URLByDeletingPathExtension?.lastPathComponent
Run Code Online (Sandbox Code Playgroud)