在Swift中,如何检查数组是否包含完整的给定子数组?例如,是否有一个contains功能如下:
let mainArray = ["hello", "world", "it's", "a", "beautiful", "day"]
contains(mainArray, ["world", "it's"]) // would return true
contains(mainArray, ["world", "it"]) // would return false
contains(mainArray, ["world", "a"]) // would return false - not adjacent in mainArray
Run Code Online (Sandbox Code Playgroud)
您可以使用更高级别的函数来完成此操作,如下所示:
func indexOf(data:[String], _ part:[String]) -> Int? {
// This is to prevent construction of a range from zero to negative
if part.count > data.count {
return nil
}
// The index of the match could not exceed data.count-part.count
return (0...data.count-part.count).indexOf {ind in
// Construct a sub-array from current index,
// and compare its content to what we are looking for.
[String](data[ind..<ind+part.count]) == part
}
}
Run Code Online (Sandbox Code Playgroud)
此函数返回第一个匹配项的索引(如果有),否则返回nil。
您可以按如下方式使用它:
let mainArray = ["hello", "world", "it's", "a", "beautiful", "day"]
if let index = indexOf(mainArray, ["world", "it's"]) {
print("Found match at \(index)")
} else {
print("No match")
}
Run Code Online (Sandbox Code Playgroud)
作为通用数组的扩展进行编辑...
现在可以将其用于任何同构Equatable类型数组。
extension Array where Element : Equatable {
func indexOfContiguous(subArray:[Element]) -> Int? {
// This is to prevent construction of a range from zero to negative
if subArray.count > self.count {
return nil
}
// The index of the match could not exceed data.count-part.count
return (0...self.count-subArray.count).indexOf { ind in
// Construct a sub-array from current index,
// and compare its content to what we are looking for.
[Element](self[ind..<ind+subArray.count]) == subArray
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1306 次 |
| 最近记录: |