在Swift String中查找Substring的所有实例的有效方法

时间:2017-12-26 18:52:56

标签: swift string swift4 string-search

Swift 4显然已经为String引入了很多新的变化。我想知道现在是否有一个内置方法可以在String中查找子字符串的所有实例。

以下是我正在寻找的东西:

let searchSentence = "hello world, hello"
let wordToMatch = "hello"

let matchingIndexArray = searchSentence.indices(of: "wordToMatch")

'matchingIndexArray'则为[0,13]

1 个答案:

答案 0 :(得分:0)

import Foundation

let searchSentence = "hello world, hello"

var searchRange = searchSentence.startIndex..<searchSentence.endIndex
var ranges: [Range<String.Index>] = []

let searchTerm = "hello"

while let range = searchSentence.range(of: searchTerm, range: searchRange) {
    ranges.append(range)
    searchRange = range.upperBound..<searchRange.upperBound
}

print(ranges.map { "(\(searchSentence.distance(from: searchSentence.startIndex, to: $0.lowerBound)), \(searchSentence.distance(from: searchSentence.startIndex, to: $0.upperBound)))" })

输出:

["(0, 5)", "(13, 18)"]