-1

I want to check whether my filename with just prefix is exist or not in Swift.

E.g

My file name is like Companies_12344

So after _ values are dynamic but "Companies_" is static.

How can i do that?

My code below For split

 func splitFilename(str: String) -> (name: String, ext: String)? {
    if let rDotIdx = find(reverse(str), "_")
    {
        let dotIdx = advance(str.endIndex, -rDotIdx)
        let fname = str[str.startIndex..<advance(dotIdx, -1)]
        println("splitFilename >> Split File Name >>\(fname)")
    }


    return nil
}
dhaval shah
  • 4,499
  • 10
  • 29
  • 42

1 Answers1

0

It's not very clear what you want to do, because your code snippet already does check if the string has the prefix.

There's a simpler way, though:

let fileName =  "Companies_12344"

if fileName.hasPrefix("Companies") {
    println("Yes, this one has 'Companies' as a prefix")
}

Swift's hasPrefix method checks if the string begins with the specified string.

Also, you could split the string easily with this:

let compos = fileName.componentsSeparatedByString("_")   // ["Companies", "12344"]

Then you could check if there's a code and grab it with:

if let fileCode = compos.last {
    println("There was a code after the prefix: \(fileCode)")
}
Eric Aya
  • 69,473
  • 35
  • 181
  • 253