字典键排序选项-按字母顺序然后按数字 [英] Dictionary Key Sort Options - Alpha then Numeric

查看:92
本文介绍了字典键排序选项-按字母顺序然后按数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

全部

我想对这种可变的数组键字典进行排序,如下所示:A-Z 0-9,但它又回来了,排序为0-9 A-Z。如何对字母进行排序,使字母字符位于数字之前?

I would like to sort this mutable dictionary of arrays keys like so: A-Z 0-9 but it's coming back sorted 0-9 A-Z. How can I sort it such that the alpha chars come before the numbers? Perhaps there is a built-in method that does this or should I create a category that extends NSString?

    NSArray *sKeysArray = [[listContent allKeys] sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
    NSString *sectionKey = [sKeysArray objectAtIndex:section];
    NSArray *sectionValues = [listContent valueForKey:sectionKey];


推荐答案

不幸的是,中没有方法NSString 将直接执行此操作。除了编写类别外,我只使用 NSArray s sortedArrayUsingComparator:方法:

Sadly there's no method in NSString that will directly do this. Instead of writing a category, I would just use NSArrays sortedArrayUsingComparator: method:

NSArray *sKeysArray = [[listContent ALlKeys] sortedArrayUsingComparator:^(id obj1, id obj2) {
// Code to compare obj1 and obj2 and return an NSComparisonResult here; return NSOrderedAscending if obj1 should come before obj2 
}];

要进行每个比较,我将使用 NSString – enumerateSubstringsInRange:options:usingBlock:传递 NSStringEnumerationByComposedCharacterSequences 作为选项(基本上枚举字符,但Unicode字符序列除外实际上是一个字母的组合)。并且,当您比较两个字符时,请使用类似于 question 来检测obj1是数字,而obj2是常规字母,并返回 NSOrderedDescending ,否则只需使用常规 compare:

To do each comparison, I would use NSString's – enumerateSubstringsInRange:options:usingBlock: passing NSStringEnumerationByComposedCharacterSequences for options (basically enumerating characters, except that unicode characters sequences which are actually one "letter" are combined). And when you're comparing two characters, use something like the answer to this question to detect when obj1 is a number and obj2 is regular letter and return NSOrderedDescending, otherwise just use regular compare:.

这篇关于字典键排序选项-按字母顺序然后按数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆