Swift find all occurrences of a substring

前端 未结 7 1957
无人及你
无人及你 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:08

    You just keep advancing the search range until you can't find any more instances of the substring:

    extension String {
        func indicesOf(string: String) -> [Int] {
            var indices = [Int]()
            var searchStartIndex = self.startIndex
    
            while searchStartIndex < self.endIndex,
                let range = self.range(of: string, range: searchStartIndex..

提交回复
热议问题