get all ranges of a substring in a string in swift

后端 未结 5 1331
时光说笑
时光说笑 2020-12-11 20:14

I have a string for example \"ab ad adk fda kla kad ab ab kd\". I want to get all range of ab.(Here ab is present at 3 position so I should get 3 range).In normal scenarion

5条回答
  •  囚心锁ツ
    2020-12-11 20:31

    Swift 5:

    The improved version of the most popular answer:

    extension String {    
        func ranges(of substring: String, options: CompareOptions = [], locale: Locale? = nil) -> [Range] {
            var ranges: [Range] = []
            while let range = range(of: substring, options: options, range: (ranges.last?.upperBound ?? self.startIndex)..

提交回复
热议问题