[英]How to get a substring from a specific character to the end of the string in swift 4?
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/Hidden/Documents/AppName/2017-07-07_21:14:52_0.jpeg
I'm trying to retrieve the full name of my image file like so: 2017-07-07_21:14:52_0.jpeg
我正在尝试检索我的图像文件的全名,如下所示:
2017-07-07_21:14:52_0.jpeg
How would I get the substring starting after the last /
to the end of the file path? 如何从文件路径的最后一个
/
结尾开始获取子字符串?
I've seen questions related to using substrings: 我见过有关使用子串的问题:
However, the provided answers did not help me with my specific problem. 但是,提供的答案并没有帮助我解决我的具体问题。
I'm sure it may be something very simple, but all I keep getting is the wrong range of substrings. 我敢肯定它可能是非常简单的东西,但我不断得到的是错误的子串范围。
Thanks! 谢谢!
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.) (代码更新为Swift 4及更高版本。)
But what you really want is the "last path component" of a file path. 但你真正想要的是文件路径的“最后路径组件”。
URL
has the appropriate method for that purpose: 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
Try this : 尝试这个 :
1) 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) 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.