Sort an array with special characters - iPhone

后端 未结 1 2001
失恋的感觉
失恋的感觉 2021-01-21 18:26

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 *descrip         


        
相关标签:
1条回答
  • 2021-01-21 18:53

    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 讨论(0)
提交回复
热议问题