arrays – Array包含一个完整的子数组

arrays – Array包含一个完整的子数组,第1张

概述在 Swift中,如何检查数组是否包含完整的给定子数组?例如,是否有一个包含这样的函数: let mainArray = ["hello", "world", "it's", "a", "beautiful", "day"]contains(mainArray, ["world", "it's"]) // would return truecontains(mainArray, ["wor 在 Swift中,如何检查数组是否包含完整的给定子数组?例如,是否有一个包含这样的函数:

let mainArray = ["hello","world","it's","a","beautiful","day"]contains(mainArray,["world","it's"])   // would return truecontains(mainArray,"it"])   // would return falsecontains(mainArray,"a"])   // would return false - not adjacent in mainArray
解决方法 您可以使用更高级别的功能来执行此 *** 作,如下所示:

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    }}

此函数返回第一个匹配的索引(如果有),否则返回nil.

您可以按如下方式使用它:

let mainArray = ["hello","day"]if let index = indexOf(mainArray,"it's"]) {    print("Found match at \(index)")} else {    print("No match")}

编辑为通用数组的扩展…

现在可以将其用于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        }    }}
总结

以上是内存溢出为你收集整理的arrays – Array包含一个完整的子数组全部内容,希望文章能够帮你解决arrays – Array包含一个完整的子数组所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/web/1018714.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-23
下一篇2022-05-23

发表评论

登录后才能评论

评论列表(0条)

    保存