Sort an array with special characters - iPhone

≡放荡痞女 提交于 2019-12-02 01:28:41

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!