我有一个NSArray NSString的,但一些字符串只是数字。如何正确排序数字? [英] I have an NSArray on NSString's, but some of the strings are only numbers. How do I sort numerically properly?

查看:82
本文介绍了我有一个NSArray NSString的,但一些字符串只是数字。如何正确排序数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的NSArray包含100,110,91,98和87,所有NSStrings。

My NSArray contains 100, 110, 91, 98, and 87, all NSStrings.

我想按照这个顺序排序:87 ,91,98,100,110。

I'd like to sort them to show up in this order: 87, 91, 98, 100, 110.

而是显示为100,110,87,91,98。

Instead they are showing up as 100, 110, 87, 91, 98.

我不能启动数组的所有int,而不是字符串。任何人都有任何想法如何判断数组是否只包含数字从字符串,可能使用for循环?然后我可以把它们所有的数组中的整数,并做这种方式排序。

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.

推荐答案

您可以使用NSString比较函数中的 NSNumericSearch 选项对字符串进行数字排序。要使用NSArray执行此操作,您需要编写一个块或函数来调用 compare:options:方法。

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];
}];

如果字符串中有一个数字, abcd89将在abcd123之前。

This will also sort numerically if there is a numer within a string, i.e. "abcd89" will come before "abcd123".

这篇关于我有一个NSArray NSString的,但一些字符串只是数字。如何正确排序数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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