【问题标题】:Custom string sorting in SwiftSwift 中的自定义字符串排序
【发布时间】:2021-08-26 00:54:46
【问题描述】:

我有一个想要按字母顺序排序的数组(大部分情况下)。例如,我希望对字符串数组进行 A-Z 排序,但以“g”开头的元素除外,我希望以“g”开头的元素在数组中是最后一个(或者如果这更容易,则在第一个)。

例子:

let list = ["apple", "car", "boat", "zebra", "ghost", "far"]

排序应该是:

["apple", "boat", "car", "far", "zebra", "ghost"]

如何做到这一点?

【问题讨论】:

    标签: ios arrays swift string sorting


    【解决方案1】:

    我会将它拆分为 2 个数组,对每个数组进行排序,然后再次组合它们。

    let list = ["apple", "car", "boat", "zebra", "ghost", "far"]
    let listWithoutG = list.filter { !$0.hasPrefix("g") }
    let listOnlyG = list.filter { $0.hasPrefix("g") }
    
    let sorted = listWithoutG.sorted() + listOnlyG.sorted()
    print("Sorted: \(sorted)")
    

    结果:

    Sorted: ["apple", "boat", "car", "far", "zebra", "ghost"]
    

    【讨论】:

      【解决方案2】:

      您可以使用sorted(by:) 并比较以“g”开头的案例,然后如果没有发生这种情况,则回退到正常的String 比较:

      let sorted = list.sorted { a, b in
          if a.first == "g" && b.first != "g" { return false }
          if b.first == "g" && a.first != "g" { return true }
          return a < b
      }
      

      【讨论】:

      • 我认为像(!$0.hasPrefix("g") &amp;&amp; $1.hasPrefix("g")) || (!$0.hasPrefix("g") &amp;&amp; $0 &lt; $1) 这样的单个表达式也可以,对吧?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-02
      • 1970-01-01
      相关资源
      最近更新 更多