修改切片从字符串到字符串的功能,以返回最后的索引(如果找不到字符串) [英] Modify slice from string to string function to return last index if to string not found

查看:119
本文介绍了修改切片从字符串到字符串的功能,以返回最后的索引(如果找不到字符串)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个切片函数,我在此处.我想知道如何修改它,以便在未找到to字符串但找到from的情况下,它将返回整个字符串(.count-1)的结束索引.现在,如果我呼叫.slice并且没有找到to字符串,显然很崩溃.

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

推荐答案

以下是一种可能的解决方案:

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.

这篇关于修改切片从字符串到字符串的功能,以返回最后的索引(如果找不到字符串)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆