How to get a substring from a specific character to the end of the string in swift 4?

后端 未结 2 1134
庸人自扰
庸人自扰 2021-01-25 19:37

I currently have a string containing a path to an image file like so:

/Users/user/Library/Developer/CoreSimulator/Devices/Hidden/data/Containers/Data/Application         


        
相关标签:
2条回答
  • 2021-01-25 20:06

    Try this :

    1)

    var str = "/Users/user/Library/Developer/CoreSimulator/Devices/Hidden/data/Containers/Data/Application/Hidden/Documents/AppName/2017-07-07_21:14:52_0.jpeg"
    let array = str.components(separatedBy: "/")
    
    print(array[array.count-1])    //2017-07-07_21:14:52_0.jpeg
    

    2)

    let str = "/Users/user/Library/Developer/CoreSimulator/Devices/Hidden/data/Containers/Data/Application/Hidden/Documents/AppName/2017-07-07_21:14:52_0.jpeg"
    
    var fileName = URL(fileURLWithPath: str).lastPathComponent
    
    print(fileName) //2017-07-07_21:14:52_0.jpeg
    
    let fileName = URL(fileURLWithPath: path).deletingPathExtension().lastPathComponent
    print(fileName) //2017-07-07_21:14:52_0
    
    0 讨论(0)
  • 2021-01-25 20:08

    To answer your direct question: You can search for the last occurrence of a string and get the substring from that position:

    let path = "/Users/user/.../AppName/2017-07-07_21:14:52_0.jpeg"
    if let r = path.range(of: "/", options: .backwards) {
        let imageName = String(path[r.upperBound...])
        print(imageName)  // 2017-07-07_21:14:52_0.jpeg
    }
    

    (Code updated for Swift 4 and later.)

    But what you really want is the "last path component" of a file path. URL has the appropriate method for that purpose:

    let path = "/Users/user/.../AppName/2017-07-07_21:14:52_0.jpeg"
    let imageName = URL(fileURLWithPath: path).lastPathComponent
    print(imageName) // 2017-07-07_21:14:52_0.jpeg
    
    0 讨论(0)
提交回复
热议问题