按字符串值对字符串的NSMutableArray进行排序 [英] Sorting an NSMutableArray of strings by string value

查看:260
本文介绍了按字符串值对字符串的NSMutableArray进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到一个包含以下字符串的字符串数组,字符串有一定的格式

I get an array of strings with the following strings, there is a certain patern to the strings

str1
str51
str3
str4
str10
str39
str31
str191

str1 str51 str3 str4 str10 str39 str31 str191

每个字符串以'str'开头并附加一个数字

Every string starts with 'str' and has a number appended onto the end of it.

是否有一种排序数组的方法,因此它按值的顺序列出字符串

Is there a neath way to sort the array so it lists the strings in order of value

str1
str3
str4
str10
str31
str39
str51
str191

str1 str3 str4 str10 str31 str39 str51 str191

我可以通过编写一些递归函数来看到这样做的方法

I can see a way to do it by writing some recursive function that will

NSString * firstString = [[strArray objectAtIndex:i].substringFromIndex:3];
NSString * secondString = [[strArray objectAtIndex:i+1].substringFromIndex:3];

if ([firstString intValue] < [secondString intValue])
{
    //do nothing they order is correct
}
else
{
    //swap the order of the 2 strings in the array
}

但那是非常基本的代码,Objective-C中是否有一些机制或一个很好的代码技巧来更好地处理这种排序?

But thats very rudimentary code, Is there some mechanism in Objective-C or a nice code trick to handle this sorting better?

非常感谢,
-Code

Many Thanks, -Code

推荐答案

如果它们都以相同的前缀开头,我相信默认排序会适当地处理它们。我的意思是:

If they all start with the same prefix, I believe that the default sort will handle them appropriately. By this, I mean:

[someArray sortUsingSelector:@selector(compare:)];

如果由于某种原因,这不起作用,那么你可以使用一个块。试试这个:

If, for some reason, this isn't working, then you can use a block. Try this:

NSArray *sortedArray = [someArray sortedArrayUsingComparator:^NSComparisonResult(id a, id b) 
{
    //Default compare, to protect against cast
    if (![a isKindOfClass:[NSString class]] || ![b isKindOfClass:[NSString class]]) {
        return ([a compare:b]);
    }
    else {
        NSString *aString = (NSString*) a;
        NSString *bString = (NSString*) b;
        int aInt = [[a.substringFromIndex:3] intValue];
        int bInt = [[b.substringFromIndex:3] intValue];
        return [aInt < bInt];
    }
}];

这篇关于按字符串值对字符串的NSMutableArray进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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