ios - 修改 slice from string to string 函数以在找不到字符串时返回最后一个索引

标签 ios swift string extension-methods

我有一个切片函数,我得到了 here .我想知道如何修改它,以便如果未找到 to 字符串,但它找到 from 它将返回整个字符串的结束索引( .count-1).现在,如果我调用 .slice 并且没有找到 to 字符串,它显然会崩溃。

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

最佳答案

这是一种可能的解决方案:

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

它不像原来的那样“花哨”,但我个人认为逻辑更容易阅读。

关于ios - 修改 slice from string to string 函数以在找不到字符串时返回最后一个索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50341541/

相关文章:

ios - 获取一个 UITableView 以在标题顶部加载

swift - Alamofire:网络错误与无效状态代码?

swift - Xcode 6 或 iOS 8 错误 : UIAlertController Not Showing Message?

ios - Swift 无法识别的选择器发送到实例 - 我错过了什么?

java - 按条件拆分和配对子字符串

c# - 子串索引许多相似的字符串

ajax - 如何让我的 JSON 不那么冗长?

ios - 在 Stanford CS193P 作业 3 (2016) 上绘制 x 与 y 图时遇到问题

ios - Xcode 5 中缺少 ViewController.xib

ios - 比较两个 UIImages Objective-c