Index of a substring in a string with Swift

前端 未结 11 1561
自闭症患者
自闭症患者 2020-11-22 14:24

I\'m used to do this in JavaScript:

var domains = \"abcde\".substring(0, \"abcde\".indexOf(\"cd\")) // Returns \"ab\"

Swift doesn\'t have t

11条回答
  •  死守一世寂寞
    2020-11-22 15:02

    Leo Dabus's answer is great. Here is my answer based on his answer using compactMap to avoid Index out of range error.

    Swift 5.1

    extension StringProtocol {
        func ranges(of targetString: Self, options: String.CompareOptions = [], locale: Locale? = nil) -> [Range] {
    
            let result: [Range] = self.indices.compactMap { startIndex in
                let targetStringEndIndex = index(startIndex, offsetBy: targetString.count, limitedBy: endIndex) ?? endIndex
                return range(of: targetString, options: options, range: startIndex..

提交回复
热议问题