我在Swift中有一个String类的扩展,它返回给定子字符串的第一个字母的索引.
任何人都可以帮助我做到这一点,它将返回所有出现的数组,而不仅仅是第一个?
谢谢.
extension String { func indexOf(string : String) -> Int { var index = -1 if let range = self.range(of : string) { if !range.isEmpty { index = distance(from : self.startIndex,to : range.lowerBound) } } return index } }
例如,而不是返回值50我想像[50,74,91,103]
您只是继续推进搜索范围,直到找不到子字符串的更多实例:
原文链接:https://www.f2er.com/swift/320148.htmlextension 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..<self.endIndex),!range.isEmpty { let index = distance(from: self.startIndex,to: range.lowerBound) indices.append(index) searchStartIndex = range.upperBound } return indices } } let keyword = "a" let html = "aaaa" let indicies = html.indicesOf(string: keyword) print(indicies) // [0,1,2,3]