Objective-C: Extract filename from path string

前端 未结 3 2018
面向向阳花
面向向阳花 2020-12-12 10:09

When I have NSString with /Users/user/Projects/thefile.ext I want to extract thefile with Objective-C methods.

What is the eas

相关标签:
3条回答
  • 2020-12-12 10:36

    If you're displaying a user-readable file name, you do not want 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.

    0 讨论(0)
  • 2020-12-12 10:52

    At the risk of being years late and off topic - and notwithstanding @Marc's excellent insight, in Swift it looks like:

    let basename = NSURL(string: "path/to/file.ext")?.URLByDeletingPathExtension?.lastPathComponent
    
    0 讨论(0)
  • 2020-12-12 11:01

    Taken from the NSString reference, you can use :

    NSString *theFileName = [[string lastPathComponent] stringByDeletingPathExtension];
    

    The lastPathComponent call will return thefile.ext, and the stringByDeletingPathExtension will remove the extension suffix from the end.

    0 讨论(0)
提交回复
热议问题