Modify slice from string to string function to return last index if to string not found

别来无恙 提交于 2020-01-15 09:41:30

问题


I have a slice function which I got here. I was wondering how I can modify it so that if the to string is not found, but it found from it will return the end index of the entire string (.count-1). Right now it's obviously crashing if I call .slice and there is no to string found.

extension String {

    func slice(from: String, to: String) -> String? {

        return (range(of: from)?.upperBound).flatMap { substringFrom in
            (range(of: to, range: substringFrom..<endIndex)?.lowerBound).map { substringTo in
                String(self[substringFrom..<substringTo])
            }
        }
    }
}

回答1:


Here's one possible solution:

extension String {
    func slice(from: String, to: String) -> String? {
        if let fromRng = range(of: from) {
            if let toRng = range(of: to, range: fromRng.upperBound..<endIndex) {
                // "from" and "to" found, get parts between
                return String(self[fromRng.upperBound..<toRng.lowerBound])
            } else {
                // "to" not found, return everything after "from"
                return String(self[fromRng.upperBound...])
            }
        } else {
            // "from" not found
            return nil
        }
    }
}

It's not as "fancy" as the original but personally I think the logic is much easier to read.



来源:https://stackoverflow.com/questions/50341541/modify-slice-from-string-to-string-function-to-return-last-index-if-to-string-no

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