【问题标题】:Find the all string in array are greater than length 4 in swift [closed]快速查找数组中的所有字符串都大于长度4 [关闭]
【发布时间】:2020-12-11 12:24:25
【问题描述】:

我已经检查了这个link。 我正在尝试获取长度大于长度 4 的字符串。 示例:

["Rama", "Bhima", "Budhaa"]

【问题讨论】:

    标签: arrays swift string


    【解决方案1】:

    如果您需要所有符合条件的值,请尝试;

    let strings: [String] = ["Rama", "Bhima", "Budhaa"]
    let filteredStrings = strings.filter { $0.count > 4 } // ["Bhima", "Budhaa"]
    

    如果您只需要符合条件的第一个值,请尝试;

    let strings: [String] = ["Rama", "Bhima", "Budhaa"]
    let filteredString = strings.first(where: { $0.count > 4 }) // optional("Bhima")
    

    【讨论】:

      【解决方案2】:

      您可以使用count method 查找字符串是否超过4 个字符,并使用filter method 创建满足大于4 个字符条件的字符串列表:

      let strings: [String] = ["Rama", "Bhima", "Budhaa"]
      let result = strings.filter { str in str.count > 4 }
      

      【讨论】:

        猜你喜欢
        • 2017-01-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-04-25
        • 2020-12-09
        • 2012-11-06
        相关资源
        最近更新 更多