Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Trim a String in Swift based on a character

Tags:

string

swift

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

I would like the result to be FfAPfl-icon.png

like image 837
Martin Muldoon Avatar asked Jul 25 '16 14:07

Martin Muldoon


1 Answers

You can use String method 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"
}
like image 126
Leo Dabus Avatar answered Nov 11 '22 07:11

Leo Dabus