【问题标题】:find repeatable string position in array [duplicate]在数组中找到可重复的字符串位置[重复]
【发布时间】:2018-11-06 07:47:16
【问题描述】:

我无法在数组中获得可重复的字符串位置。我的代码是这样的:

var startDates : [String] = ["06/11/2018", "16/11/2018", "26/11/2018", "06/11/2018"]
var nomor : [Int] = []
for date in startDates {
        if startDates.contains(where: {
            $0.range(of: "06/11/2018", options: .caseInsensitive) != nil
        }) == true {
            let nomornya = startDates.index(of: "06/11/2018")!
            nomor.append(nomornya)
        }
    }
    print("nomornya:\(nomor)")

结果:

nomornya:[0, 0, 0, 0]

我想变成这样:

nomornya:[0, 3]

执行此操作的正确代码是什么?

【问题讨论】:

  • 如果有多个日期重复,输出会是什么?
  • 功能是从日历中获取所有事件,其中一个日期可以有多个事件标题,所以我必须得到位置
  • 你想在这里做什么?这些字符串看起来像日期,但您将它们作为字符串处理。看起来可能有更好的方法来做你想做的事情。
  • ["06/11/2018", "16/11/2018", "26/11/2018", "06/11/2018", "16/11/2018"] 的预期输出是什么?
  • @Sweeper 结果必须是 [0,3]

标签: arrays swift string


【解决方案1】:

您希望项目的索引与特定日期匹配,因此过滤索引:

let startDates = ["06/11/2018", "16/11/2018", "26/11/2018", "06/11/2018"]
let nomor = startDates.indices.filter{ startDates[$0] == "06/11/2018" } // [0, 3]

【讨论】:

    【解决方案2】:
    let date = "06/11/2018"
    var matchingIndices = [Int]()
    for (index, startDate) in startDates.enumerated() {
        if date == startDate {
            matchingIndices.append(index)
        }
    }
    

    您想在列表中迭代一次并注意匹配的索引。这应该符合您的预期输出。

    【讨论】:

    • 这个也对,但是代码比较长
    猜你喜欢
    • 1970-01-01
    • 2021-05-24
    • 1970-01-01
    • 2014-06-23
    • 1970-01-01
    • 2011-01-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多