我在 NSString 上有一个 NSArray,但有些字符串只是数字.如何正确地按数字排序? [英] I have an NSArray on NSString's, but some of the strings are only numbers. How do I sort numerically properly?
问题描述
My NSArray contains 100, 110, 91, 98, and 87, all NSStrings.
I'd like to sort them to show up in this order: 87, 91, 98, 100, 110.
Instead they are showing up as 100, 110, 87, 91, 98.
I can't start the array with all ints instead of strings unfortunately. Anyone have any ideas on how to tell if the array contains ONLY numbers from strings, maybe using a for loop? Then I could just convert them all to ints within the array and do the sort that way. Or maybe there is an easy way I am missing?
Let me know if anyone has any ideas.
You can use the NSNumericSearch
option to the NSString compare function to sort strings numerically. To do this with an NSArray, you will need to write a block or function to call the compare:options:
method.
NSArray *theStrings; // Contains strings, some of which are numbers
NSArray *theSortedStrings = [theStrings sortedArrayUsingComparator:^(id obj1, id obj2) {
return [(NSString *)obj1 compare:(NSString *)obj2 options:NSNumericSearch];
}];
This will also sort numerically if there is a numer within a string, i.e. "abcd89"
will come before "abcd123"
.
这篇关于我在 NSString 上有一个 NSArray,但有些字符串只是数字.如何正确地按数字排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!