How to split filename from file extension in Swift?

前端 未结 21 1907
陌清茗
陌清茗 2020-12-01 03:24

Given the name of a file in the bundle, I want load the file into my Swift app. So I need to use this method:

let soundURL = NSBundle.mainBundle().URLForReso         


        
相关标签:
21条回答
  • 2020-12-01 03:46

    Strings in Swift can definitely by tricky. If you want a pure Swift method, here's how I would do it:

    1. Use find to find the last occurrence of a "." in the reverse of the string
    2. Use advance to get the correct index of the "." in the original string
    3. Use String's subscript function that takes an IntervalType to get the strings
    4. Package this all up in a function that returns an optional tuple of the name and extension

    Something like this:

    func splitFilename(str: String) -> (name: String, ext: String)? {
        if let rDotIdx = find(reverse(str), ".") {
            let dotIdx = advance(str.endIndex, -rDotIdx)
            let fname = str[str.startIndex..<advance(dotIdx, -1)]
            let ext = str[dotIdx..<str.endIndex]
            return (fname, ext)
        }
        return nil
    }
    

    Which would be used like:

    let str = "/Users/me/Documents/Something.something/text.txt"
    if let split = splitFilename(str) {
        println(split.name)
        println(split.ext)
    }
    

    Which outputs:

    /Users/me/Documents/Something.something/text
    txt
    

    Or, just use the already available NSString methods like pathExtension and stringByDeletingPathExtension.

    0 讨论(0)
  • 2020-12-01 03:46

    Swift 3.x extended solution:

    extension String {
        func lastPathComponent(withExtension: Bool = true) -> String {
            let lpc = self.nsString.lastPathComponent
            return withExtension ? lpc : lpc.nsString.deletingPathExtension
        }
    
        var nsString: NSString {
             return NSString(string: self)
        }
    }
    
    let path = "/very/long/path/to/filename_v123.456.plist"
    let filename = path.lastPathComponent(withExtension: false)
    

    filename constant now contains "filename_v123.456"

    0 讨论(0)
  • 2020-12-01 03:48

    Swift 5

    URL.deletingPathExtension().lastPathComponent
    
    0 讨论(0)
  • 2020-12-01 03:51

    A better way (or at least an alternative in Swift 2.0) is to use the String pathComponents property. This splits the pathname into an array of strings. e.g

    if let pathComponents = filePath.pathComponents {
        if let last = pathComponents.last {
            print(" The last component is \(last)") // This would be the extension
            // Getting the last but one component is a bit harder
            // Note the edge case of a string with no delimiters!
        }
    }
    // Otherwise you're out of luck, this wasn't a path name!
    
    0 讨论(0)
  • 2020-12-01 03:52

    They got rid of pathExtension for whatever reason.

    let str = "Hello/this/is/a/filepath/file.ext"
    let l = str.componentsSeparatedByString("/")
    let file = l.last?.componentsSeparatedByString(".")[0]
    let ext = l.last?.componentsSeparatedByString(".")[1]
    
    0 讨论(0)
  • 2020-12-01 03:55

    In Swift you can change to NSString to get extension faster:

    extension String {
        func getPathExtension() -> String {
            return (self as NSString).pathExtension
        }
    }
    
    0 讨论(0)
提交回复
热议问题