按字符串中包含的数字对 NSString 的 NSArray 进行排序。重新排列字符串,使数字位于开头?

发布于 2024-11-07 08:01:57 字数 569 浏览 0 评论 0原文

我有一个字符串数组,如下所示,

"/var/folders/zy/zy4FzDGQEUuq9jZ1hTRFHk+++TI/-Tmp-/tarDir0172809001305545247/0516_GTB_HP_01.pdf"
"/var/folders/zy/zy4FzDGQEUuq9jZ1hTRFHk+++TI/-Tmp-/tarDir0172809001305545247/0516_ETB_HP_28.pdf"

如您所见,它们的不同之处在于数字和字符 GE。 当我像这样对它们进行排序时,它们会按 GTB / ETB 排序,然后按末尾的数字排序。但我想要的是首先按数字排序,然后按字母 E 或 G 排序。 我应该提到的是,可能会出现结尾具有相同编号的字符串,只是 GE 有所不同。

所以我想到的可能就是简单地将最后的数字与字符 ETBGTB 交换。 最优雅的方法是什么? 或者你还有其他建议吗? 谢谢!

I have an array of string, that look like this

"/var/folders/zy/zy4FzDGQEUuq9jZ1hTRFHk+++TI/-Tmp-/tarDir0172809001305545247/0516_GTB_HP_01.pdf"
"/var/folders/zy/zy4FzDGQEUuq9jZ1hTRFHk+++TI/-Tmp-/tarDir0172809001305545247/0516_ETB_HP_28.pdf"

As you can see, tehy differ by the number and the character G or E.
When I sort them like this, they are sorted by GTB / ETB and then by the number at the end. But what I want is first to have them sorted by number and then by the letter E or G.
What I should mention is, that there can occur Strings that have the same number in the end and just differ by G or E.

So what I thought of, was maybe simply exchanging the number in the end with the characters ETB or GTB.
What's the most elegant way to do this?
Or do u have any other suggestion?
Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

也只是曾经 2024-11-14 08:01:57

您可以使用自定义比较器在 NSArray 或 NSMutableArray 中进行排序。在该函数内,您可以将字符串拆分为多个部分,并按照您想要的方式比较它们(首先是数字,如果它们相等则 GTB / ETB)

you can use a custom comparator for your sort in NSArray or NSMutableArray. Inside that function you could split the string in multiple parts and compare them the way you want (first the numbers, and if those are equal the GTB / ETB)

叶落知秋 2024-11-14 08:01:57

如果您可以针对 iOS 4.x 及更高版本,则可以使用块

NSArray *sortedArray = [array sortedArrayUsingComparator: ^(id obj1, id obj2) {

    // obj1 and obj2 are 2 strings from you array
    // here you write your own logic to understand if obj1 <=> obj2
    // here's an example in pseudo code
    if (obj1 > obj2)
        return (NSComparisonResult)NSOrderedDescending;
    if (obj1 < obj2)
        return (NSComparisonResult)NSOrderedAscending;
    return (NSComparisonResult)NSOrderedSame;
}];

If you can target iOS 4.x and above you can use blocks

NSArray *sortedArray = [array sortedArrayUsingComparator: ^(id obj1, id obj2) {

    // obj1 and obj2 are 2 strings from you array
    // here you write your own logic to understand if obj1 <=> obj2
    // here's an example in pseudo code
    if (obj1 > obj2)
        return (NSComparisonResult)NSOrderedDescending;
    if (obj1 < obj2)
        return (NSComparisonResult)NSOrderedAscending;
    return (NSComparisonResult)NSOrderedSame;
}];
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文