字典键排序选项 - 字母然后数字
所有,
我想对这个可变数组键字典进行排序,如下所示:AZ 0-9,但它返回排序0-9 AZ。如何对其进行排序,使字母字符位于数字之前?也许有一个内置方法可以做到这一点,或者我应该创建一个扩展 NSString 的类别?
NSArray *sKeysArray = [[listContent allKeys] sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
NSString *sectionKey = [sKeysArray objectAtIndex:section];
NSArray *sectionValues = [listContent valueForKey:sectionKey];
All,
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];
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
遗憾的是,
NSString
中没有方法可以直接执行此操作。我不编写类别,而是使用NSArray
的sortedArrayUsingComparator:
方法:为了进行每次比较,我将使用
NSString
的– enumerateSubstringsInRange:options:usingBlock:
传递NSStringEnumerationByComposedCharacterSequences
选项(基本上枚举字符,除了 unicode 字符序列实际上是一个“字母”的组合)。当您比较两个字符时,请使用类似于此问题<的答案/a> 检测 obj1 是否为数字且 obj2 是否为常规字母并返回 NSOrderedDescending,否则仅使用常规比较:。Sadly there's no method in
NSString
that will directly do this. Instead of writing a category, I would just useNSArray
ssortedArrayUsingComparator:
method:To do each comparison, I would use
NSString
's– enumerateSubstringsInRange:options:usingBlock:
passingNSStringEnumerationByComposedCharacterSequences
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 returnNSOrderedDescending
, otherwise just use regularcompare:
.就像@yuri所说,
sortedArrayUsingComparator:
应该提供基本功能。这是一个简单的版本,它将以十进制数字开头的字符串排序在以字母字符开头的字符串(在
NSCharacterSet
的定义中)之后,并将所有其他字符串组合保留为其默认排序顺序:它不会正确处理由十进制数字作为第一个组成部分组成的 unicode 字母,但我会认为这是一个病态的情况,直到有人能启发我。
Like @yuri says,
sortedArrayUsingComparator:
should provide the basic functionality.Here is a simple version that sorts strings beginning with a decimal digit after strings beginning with an alphabetic character (in
NSCharacterSet
's definition), and leaves all other combinations of strings to their default sort order:Caveat: It will not handle a unicode letter composed of a decimal digit as the first component correctly, but I will consider that a pathological case until someone can enlighten me.