如何用字母数字值对数组排序? [英] How to sort an array with alphanumeric values?

查看:118
本文介绍了如何用字母数字值对数组排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组,其中包含诸如frame_10@3x.png,frame_5 @ 3x.png,frame_19 @ 3x.png等字符串. 所以我想根据下划线后的数字对该数组进行排序,即正确的序列为frame_5 @ 3x.png,frame_10 @ 3x.png,frame_19 @ 3x.png.

I have an array which contains strings like frame_10@3x.png , frame_5@3x.png,frame_19@3x.png etc. So I want to sort this array according to the number after the underscore i.e. the correct sequence will be frame_5@3x.png,frame_10@3x.png,frame_19@3x.png.

我尝试使用以下方法,但没有结果:

I tried to use the following method but no result:

NSInteger firstNumSort(id str1, id str2, void *context) {
    int num1 = [str1 integerValue];
    int num2 = [str2 integerValue];

    if (num1 < num2)
        return NSOrderedAscending;
    else if (num1 > num2)
        return NSOrderedDescending;

    return NSOrderedSame;
}

请建议如何对数组进行排序.

Please suggest how to do this sorting for array.

推荐答案

NSArray *sry_img = [[NSArray alloc]    initWithObjects:@"frame_18@3x.png",@"frame_17@3x.png",@"frame_1222@3x.png",@"frame_10@3x.png",@"frame_3@3x.png",@"frame_4@3x.png",@"frame_4@3x.png",@"frame_1@3x.png",@"frame_4@3x.png",@"frame_4@3x.png",nil];
  NSArray *sortedStrings  = [sry_img sortedArrayUsingSelector:@selector(localizedStandardCompare:)];

NSLog(@"%@",sortedStrings);

Enjy .......

Enjy .......

但是 只要在适合于类似Finder排序的列表和表中显示文件名或其他字符串,就应使用在10.6中添加的localizedStandardCompare:.此方法的确切行为可能会在将来的版本中进行调整,并且在不同的本地化情况下会有所不同,因此客户端不应依赖于字符串的确切排序顺序.

But localizedStandardCompare:, added in 10.6, should be used whenever file names or other strings are presented in lists and tables where Finder-like sorting is appropriate. The exact behavior of this method may be tweaked in future releases, and will be different under different localizations, so clients should not depend on the exact sorting order of the strings.

这篇关于如何用字母数字值对数组排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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