如何基于字符修剪Swift中的字符串

时间:2016-07-25 14:15:33

标签: swift string

我想修剪这个字符串,这样我就可以提取文件名,后面总是以“_”(下划线)开头。这样做的最佳方式是什么?

https://s3.amazonaws.com/brewerydbapi/beer/RXI2cT/upload_FfAPfl-icon.png

我希望结果是FfAPfl-icon.png

3 个答案:

答案 0 :(得分:6)

您可以使用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

if let range = link.range(of: "_") {
    let fileName = link.substring(from: range.upperBound)
    print(fileName) // "FfAPfl-icon.png\n"
}

答案 1 :(得分:3)

由于它是一个URL,您可以通过以下方式访问该字符串:

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")

在Swift 2.2或3版中

let url = NSURL(string: 
let component = url?.lastPathComponent?.characters.split{$0 == "_"}.map(String.init)

print(component?.last)

答案 2 :(得分: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)")


 }