如何从特定字符到swift 4中的字符串末尾获取子字符串?

时间:2017-07-08 05:25:56

标签: ios swift

我目前有一个包含图像文件路径的字符串,如下所示:

/Users/user/Library/Developer/CoreSimulator/Devices/Hidden/data/Containers/Data/Application/Hidden/Documents/AppName/2017-07-07_21:14:52_0.jpeg

我正在尝试检索我的图片文件的全名,如下所示:2017-07-07_21:14:52_0.jpeg

如何从最后/之后的文件路径末尾开始获取子字符串?

我见过与使用子字符串相关的问题:

  1. Swift: How to get substring from start to last index of character
  2. How does String substring work in Swift 3
  3. Substring from String in Swift
  4. 但是,提供的答案并没有帮助我解决我的具体问题。

    我确信这可能是非常简单的事情,但我所得到的只是错误的子串范围。

    谢谢!

2 个答案:

答案 0 :(得分:3)

回答您的直接问题:您可以搜索最后一个问题 出现一个字符串并从该位置获取子字符串:

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

真正想要的是文件路径的“最后路径组件”。 URL有适当的方法用于此目的:

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

答案 1 :(得分:0)

试试这个:

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