gpt4 book ai didi

ios - 排序核心数据

转载 作者:行者123 更新时间:2023-12-01 18:40:04 24 4
gpt4 key购买 nike

我有一些字符串和整数混合的数据,

"003G"
"002P"
"001P"
"018P"
"002G"
"019P"
"001G"
"020P"
"012P"
"011P"
"012G"
"013P"
"007P"
"011G"
"010P"
"009P"
"008P"
"005P"
"006P"
"014P"
"007G"
"010G"
"009G"
"008G"
"015P"
"006G"
"005Ga"
"004P"
"016P"
"005G"
"004G"
"003P"
"017P"

需要像这样的输出:
"001P"
"002P"
"003P"
"004P"
"005P"
"006P"
"007P"
"008P"
"009P"
"010P"
"011P"
"012P"
"013P"
"014P"
"015P"
"016P"
"017P"
"018P"
"019P"
"020P"
"001G"
"002G"
"003G"
"004G"
"005G"
"005Ga"
"006G"
"007G"
"008G"
"009G"
"010G"
"011G"
"012G"

同时Android使用 *[0-9,0P-9P,0G-9G]进行了排序

最佳答案

这是一个非常不寻常的排序顺序。您必须使用Comparator编写自定义描述符

需要两个描述符。

  • 排序第四个字符降序
    let sortDescriptor1 = NSSortDescriptor(key: "referenceNo", ascending: false) { (obj1, obj2)  -> ComparisonResult in
    let string1 = obj1 as! String
    let string2 = obj2 as! String
    let fourthChar1 = string1.index(string1.startIndex, offsetBy: 3)
    let fourthChar2 = string2.index(string2.startIndex, offsetBy: 3)
    return String(string1[fourthChar1]).compare(String(string2[fourthChar2]))
    }
  • 使用numeric选项对前3个字符进行升序排序,并考虑xxxxa的大小写
    let sortDescriptor2 = NSSortDescriptor(key: "referenceNo", ascending: true) { (obj1, obj2)  -> ComparisonResult in
    let string1 = obj1 as! String
    let string2 = obj2 as! String
    let fourthChar1 = string1.index(string1.startIndex, offsetBy: 3)
    let fourthChar2 = string2.index(string2.startIndex, offsetBy: 3)
    let orderedResult = string1.substring(to: fourthChar1).compare(string2.substring(to: fourthChar2), options: .numeric)
    if orderedResult == .orderedSame {
    return string1.characters.count < string2.characters.count ? .orderedAscending : .orderedDescending
    } else {
    return orderedResult
    }
    }

  • 当然,这假定值是在ASCII范围内始终为4个字符或更多的字符串。

    关于ios - 排序核心数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44694471/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com