I would like to trim this string, so that I can extract the filename, which is always preceded by an "_" (underscore). What is the best way to do this?
我想修剪这个字符串,以便我可以提取文件名,后面总是以“_”(下划线)开头。做这个的最好方式是什么?
https://s3.amazonaws.com/brewerydbapi/beer/RXI2cT/upload_FfAPfl-icon.png
https://s3.amazonaws.com/brewerydbapi/beer/RXI2cT/upload_FfAPfl-icon.png
I would like the result to be FfAPfl-icon.png
我希望结果是FfAPfl-icon.png
3 个解决方案
#1
6
You can use String method rangeOfString:
您可以使用String方法rangeOfString:
let link = "https://s3.amazonaws.com/brewerydbapi/beer/RXI2cT/upload_FfAPfl-icon.png"
if let range = link.rangeOfString("_") {
let fileName = link.substringFromIndex(range.endIndex)
print(fileName) // "FfAPfl-icon.png\n"
}
Xcode 8 beta 3 • Swift 3
Xcode 8 beta 3•Swift 3
if let range = link.range(of: "_") {
let fileName = link.substring(from: range.upperBound)
print(fileName) // "FfAPfl-icon.png\n"
}
#2
3
Since it is an URL, you can get to the string via:
由于它是一个URL,您可以通过以下方式访问该字符串:
Swift version 3
Swift版本3
let url = URL(string: "https://s3.amazonaws.com/brewerydbapi/beer/RXI2cT/upload_FfAPfl-icon.png")
let component = url?.lastPathComponent?.characters.split(separator:"_").map(String.init)
print(component?.last)// Optional("FfAPfl-icon.png")
In Swift version 2.2 or 3
在Swift 2.2或3版中
let url = NSURL(string:
let component = url?.lastPathComponent?.characters.split{$0 == "_"}.map(String.init)
print(component?.last)
#3
0
For swift 3.X and swift 4.0
对于swift 3.X和swift 4.0
let strUrl = "https://www.youtube.com/watch?v=HUNcbm9sLaY"
if let range = strUrl.range(of: "=") {
let strIdentifier = strUrl.substring(from: range.upperBound)
print("Identifier:\(strIdentifier)")
}
#1
6
You can use String method rangeOfString:
您可以使用String方法rangeOfString:
let link = "https://s3.amazonaws.com/brewerydbapi/beer/RXI2cT/upload_FfAPfl-icon.png"
if let range = link.rangeOfString("_") {
let fileName = link.substringFromIndex(range.endIndex)
print(fileName) // "FfAPfl-icon.png\n"
}
Xcode 8 beta 3 • Swift 3
Xcode 8 beta 3•Swift 3
if let range = link.range(of: "_") {
let fileName = link.substring(from: range.upperBound)
print(fileName) // "FfAPfl-icon.png\n"
}
#2
3
Since it is an URL, you can get to the string via:
由于它是一个URL,您可以通过以下方式访问该字符串:
Swift version 3
Swift版本3
let url = URL(string: "https://s3.amazonaws.com/brewerydbapi/beer/RXI2cT/upload_FfAPfl-icon.png")
let component = url?.lastPathComponent?.characters.split(separator:"_").map(String.init)
print(component?.last)// Optional("FfAPfl-icon.png")
In Swift version 2.2 or 3
在Swift 2.2或3版中
let url = NSURL(string:
let component = url?.lastPathComponent?.characters.split{$0 == "_"}.map(String.init)
print(component?.last)
#3
0
For swift 3.X and swift 4.0
对于swift 3.X和swift 4.0
let strUrl = "https://www.youtube.com/watch?v=HUNcbm9sLaY"
if let range = strUrl.range(of: "=") {
let strIdentifier = strUrl.substring(from: range.upperBound)
print("Identifier:\(strIdentifier)")
}