check Filename is exist by prefix in Swift

£可爱£侵袭症+ 提交于 2019-12-13 23:35:11

问题


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
}

回答1:


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


来源:https://stackoverflow.com/questions/31295161/check-filename-is-exist-by-prefix-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!