在iOS中对包含字母数字单词的数组进行排序 [英] Sort array that contain alphanumeric words in iOS

查看:328
本文介绍了在iOS中对包含字母数字单词的数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含10个元素的数组,这些元素被称为产品,默认排序,这是当前的日志。

I have a array with 10 elements called products which is sorted by default, this is the current log now.

for (int i=0;i<products.count; i++)
{
     NSLog(@"%@",products[i]);
}

输出:

Product1
Product10
Product2
Product3
Product4
Product5
Product6
Product7
Product8
Product9

我需要按以下顺序对其进行排序:

I need to sort it in following order:

Product1
Product2
Product3
Product4
Product5
Product6
Product7
Product8
Product9
Product10

我目前的方法是扫描基于这个数字和排序,我想知道在iOS中是否有任何其他方式或默认方法可以做到这一点,还是我必须坚持使用我当前的扫描每个元素中的数字然后排序的方法? / p>

My current method is to scan out the numbers and sort based on that, I was wondering if there is any other way or and default method in iOS that does this or should I have to stick with my current method of scanning the numbers in each element and then sort??

推荐答案

您可以使用此代码对数组进行排序。使用 NSNumericSearch 搜索字符串中的数值。

You can use this code to sort array. Use NSNumericSearch to search the numeric value in string.

NSArray * products = [[NSArray alloc] initWithObjects:@"Product1",
                                                      @"Product10",
                                                      @"Product2",
                                                      @"Product3",
                                                      @"Product4",
                                                      @"Product5",
                                                      @"Product6",
                                                      @"Product7",
                                                      @"Product8",
                                                      @"Product9",
                                                      nil];

products = [products sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        return [(NSString *)obj1 compare:(NSString *)obj2 options:NSNumericSearch];
    }];

NSLog(@"products : %@", products);

并显示日志:

products : (
    Product1,
    Product2,
    Product3,
    Product4,
    Product5,
    Product6,
    Product7,
    Product8,
    Product9,
    Product10
)

这篇关于在iOS中对包含字母数字单词的数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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