我习惯于在
JavaScript中执行此操作:
var domains = "abcde".substring(0,"abcde".indexOf("cd")) // Returns "ab"
Swift没有这个功能,怎么做类似的事情?
Xcode 8.3.1•Swift 3.1
原文链接:https://www.f2er.com/swift/319663.htmlextension 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}]