Swift find all occurrences of a substring

前端 未结 7 1966
无人及你
无人及你 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 00:59

    I have tweaked the accepted answer so that case sensitivity can be configured

    extension String {
        func allIndexes(of subString: String, caseSensitive: Bool = true) -> [Int] {
            let subString = caseSensitive ? subString : subString.lowercased()
            let mainString = caseSensitive ? self : self.lowercased()
            var indices = [Int]()
            var searchStartIndex = mainString.startIndex
            while searchStartIndex < mainString.endIndex,
                let range = mainString.range(of: subString, range: searchStartIndex..

提交回复
热议问题