开发者

Sort an array with special characters - iPhone

开发者 https://www.devze.com 2022-12-23 23:13 出处:网络
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:

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开发者_JAVA百科 sortedArrayUsingDescriptors:sortDescriptors];

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

Thanks


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

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

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

Edit: Here’s the long story:

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

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
0

精彩评论

暂无评论...
验证码 换一张
取 消