Martin Muldoon Martin Muldoon - 2 months ago 5x
Swift Question

How to Trim a String in Swift based on a character

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?

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


You can use String method rangeOfString:

let link = ""
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"