Swift find all occurrences of a substring

前端 未结 7 1979
无人及你
无人及你 2020-12-06 00:46

I have an extension here of the String class in Swift that returns the index of the first letter of a given substring.

Can anybody please help me make it so it will

7条回答
  •  渐次进展
    2020-12-06 01:04

    This could be done with recursive method. I used a numeric string to test it. It returns an optional array of Int, meaning it will be nil if no substring can be found.

    extension String {
        func indexes(of string: String, offset: Int = 0) -> [Int]? {
            if let range = self.range(of : string) {
                if !range.isEmpty {
                    let index = distance(from : self.startIndex, to : range.lowerBound) + offset
                    var result = [index]
                    let substr = self.substring(from: range.upperBound)
                    if let substrIndexes = substr.indexes(of: string, offset: index + distance(from: range.lowerBound, to: range.upperBound)) {
                        result.append(contentsOf: substrIndexes)
                    }
                    return result
                }
            }
            return nil
        }
    }
    
    let numericString = "01234567890123456789012345678901234567890123456789012345678901234567890123456789"
    numericString.indexes(of: "3456")
    

提交回复
热议问题