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

前端之家收集整理的这篇文章主要介绍了使用Swift的字符串中的子字符串索引前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我习惯于在 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}]

猜你在找的Swift相关文章