用特殊字符对数组进行排序-iPhone [英] Sort an array with special characters - iPhone

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

问题描述

我有一个带有法语字符串的数组,可以说:égrener"和"exact",我想对它进行排序,例如égrener是第一个.当我这样做时:

I have an array with french strings let say: "égrener" and "exact" I would like to sort it such as égrener is the first. When I do:

NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObject:descriptor];
NSArray *sortedArray = [myArray sortedArrayUsingDescriptors:sortDescriptors];

我在列表的末尾得到é...我该怎么办?

I get the é at the end of the list... What should I do?

谢谢

推荐答案

NSString中有一个方便的方法,可让您轻松进行这种类型的排序:

There’s a convenience method in NSString that lets you do this type of sorting easily:

NSArray *sortedArray = [myArray sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];

NSString的基础比较方法(

NSString’s underlying comparison method (compare:options:range:locale:) gives you even more options of how sorting should be done.

这是长篇小说:

首先,定义一个比较函数.这对自然字符串排序很有用:

First, define a comparison function. This one is good for natural string sorting:

static NSInteger comparator(id a, id b, void* context)
{
    NSInteger options = NSCaseInsensitiveSearch
        | NSNumericSearch              // Numbers are compared using numeric value
        | NSDiacriticInsensitiveSearch // Ignores diacritics (â == á == a)
        | NSWidthInsensitiveSearch;    // Unicode special width is ignored

    return [(NSString*)a compare:b options:options];
}

然后,对数组进行排序.

Then, sort the array.

    NSArray* myArray = [NSArray arrayWithObjects:@"foo_002", @"fôõ_1", @"fôõ_3", @"foo_0", @"foo_1.5", nil];
    NSArray* sortedArray = [myArray sortedArrayUsingFunction:comparator context:NULL];

该示例中的数组包含一些有趣的字符:数字,变音标记和unicode范围ff00中的某些字符.最后一个字符类型看起来像ASCII字符,但以不同的宽度打印.

The array in the example contains some funny characters: Numbers, diacritical marks, and some characters from unicode range ff00. The last character type looks like an ASCII character but is printed in a different width.

使用的比较功能以人类可预测的方式处理所有情况.排序后的数组具有以下顺序:

The used comparison function handles all cases in human predictable way. The sorted array has the following order:

foo_0
fôõ_1
foo_1.5
foo_002
fôõ_3

这篇关于用特殊字符对数组进行排序-iPhone的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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