按字符串中包含的数字对 NSString 的 NSArray 进行排序。重新排列字符串,使数字位于开头?
我有一个字符串数组,如下所示,
"/var/folders/zy/zy4FzDGQEUuq9jZ1hTRFHk+++TI/-Tmp-/tarDir0172809001305545247/0516_GTB_HP_01.pdf"
"/var/folders/zy/zy4FzDGQEUuq9jZ1hTRFHk+++TI/-Tmp-/tarDir0172809001305545247/0516_ETB_HP_28.pdf"
如您所见,它们的不同之处在于数字和字符 G
或 E
。 当我像这样对它们进行排序时,它们会按 GTB
/ ETB
排序,然后按末尾的数字排序。但我想要的是首先按数字排序,然后按字母 E 或 G 排序。 我应该提到的是,可能会出现结尾具有相同编号的字符串,只是 G
或 E
有所不同。
所以我想到的可能就是简单地将最后的数字与字符 ETB
或 GTB
交换。 最优雅的方法是什么? 或者你还有其他建议吗? 谢谢!
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用自定义比较器在 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)
如果您可以针对 iOS 4.x 及更高版本,则可以使用块
If you can target iOS 4.x and above you can use blocks