加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

使用Swift的字符串中的子字符串索引

发布时间:2020-12-14 05:35:03 所属栏目:百科 来源:网络整理
导读:我习惯于在 JavaScript中执行此操作: var domains = "abcde".substring(0,"abcde".indexOf("cd")) // Returns "ab" Swift没有这个功能,怎么做类似的事情? Xcode 8.3.1?Swift 3.1 extension String { func index(of string: String,options: CompareOptions
我习惯于在 JavaScript中执行此操作:
var domains = "abcde".substring(0,"abcde".indexOf("cd")) // Returns "ab"

Swift没有这个功能,怎么做类似的事情?

Xcode 8.3.1?Swift 3.1
extension String {
    func index(of string: String,options: CompareOptions = .literal) -> Index? {
        return range(of: string,options: options)?.lowerBound
    }
    func endIndex(of string: String,options: options)?.upperBound
    }
    func indexes(of string: String,options: CompareOptions = .literal) -> [Index] {
        var result: [Index] = []
        var start = startIndex
        while let range = range(of: string,options: options,range: start..<endIndex) {
            result.append(range.lowerBound)
            start = range.upperBound
        }
        return result
    }
    func ranges(of string: String,options: CompareOptions = .literal) -> [Range<Index>] {
        var result: [Range<Index>] = []
        var start = startIndex
        while let range = range(of: string,range: start..<endIndex) {
            result.append(range)
            start = range.upperBound
        }
        return result
    }
}

用法:

let str = "Hello,playground,playground"
str.index(of: "play")      // 7
str.endIndex(of: "play")   // 11
str.indexes(of: "play")    // [7,19,31]
str.ranges(of: "play")     // [{lowerBound 7,upperBound 11},{lowerBound 19,upperBound 23},{lowerBound 31,upperBound 35}]

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读