简体   繁体   中英

How to delete last path component of a String in Swift?

I have a String 11/Passion/01PassionAwakening.mp3 and I need to delete the last path component 01PassionAwakening.mp3 in order to get 11/Passion .

How can I do this while saving both components?

You can separate your url into two parts like so:

let str : NSString = "www.music.com/Passion/PassionAwakening.mp3" 
let path : NSString = str.stringByDeletingLastPathComponent
let ext : NSString = str.lastPathComponent

print(path)
print(ext)

Output

www.music.com/Passion
PassionAwakening.mp3

For more info please have a look at this link .

You should really do away with legacy NS Objective-C classes and manual path string splitting where possible. Use URL instead:

let url = URL(fileURLWithPath: "a/b/c.dat", isDirectory: false)
let path = url.deletingLastPathComponent().relativePath // 'a/b'
let file = url.lastPathComponent // 'c.dat'

That being said, Apple has an explicit FilePath type starting with macOS 11, but with no path manipulation methods. For those you'd have to include the external system package

If you are on macOS 12, the methods from the external package are now also available on the system.

Swift 4+:

let components = path.split(separator: "/")
let directory = components.dropLast(1).map(String.init).joined(separator: "/")

Swift 3:

let str = "11/Passion/01PassionAwakening.mp3"
if !str.isEmpty {
    let components = str.characters.split("/")
    let head = components.dropLast(1).map(String.init).joinWithSeparator("/")
    let tail = components.dropFirst(components.count-1).map(String.init)[0]

    print("head:",head,"tail:", tail) // head: 11/Passion tail: 01PassionAwakening.mp3
} else {
    print("path should not be an empty string!")
}

这也适用于 Swift 3.0:

let fileName = NSString(string: "11/Passion/01PassionAwakening.mp3").lastPathComponent

Swift 3.0 version

if !str.isEmpty {
        let components = str.characters.split(separator: "/")
        let head = components.dropLast(1).map(String.init).joined(separator: "/")
        let words = components.count-1
        let tail = components.dropFirst(words).map(String.init)[0]

        print("head:",head,"tail:", tail) // head: 11/Passion tail: 01PassionAwakening.mp3
    } else {
        print("path should not be an empty string!")
    }

rolling back to NSString:

extension String {

var ns: NSString {
    return self as NSString
}

var pathExtension: String {
    return ns.pathExtension
}

var lastPathComponent: String {
    return ns.lastPathComponent
}

var stringByDeletingLastPathComponent: String {
    return ns.deletingLastPathComponent
}

}

so you can do:

let folderPath = pathString.stringByDeletingLastPathComponent

Just improvised the solution for URL String. Thank you so much ingconti

extension String {

    var ns: URL? {
        return URL.init(string: self)
    }

    var pathExtension: String {
        return ns?.pathExtension ?? ""
    }

    var lastPathComponent: String {
        return ns?.lastPathComponent ?? ""
    }

    var stringByDeletingLastPathComponent: String {
        return ns?.deletingLastPathComponent().absoluteString ?? ""
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM