How can I sort an array of strings alphabetically when the strings contains åäö?

后端 未结 1 1264
半阙折子戏
半阙折子戏 2021-01-02 17:07

I\'m building an app in xcode4.3/Objective-C and have come across a problem when trying to sort an NSMutableArray. I\'ll populate it with strings from a sqlite database. The

相关标签:
1条回答
  • 2021-01-02 17:36

    You can make it work by using compare:options:range:locale: and specifying Swedish locale explicitly, like this:

    NSArray *strings=[NSArray arrayWithObjects:@"as", @"ol", @"st", @"br", @"ög", @"år", @"ös", nil];
    NSLocale *locale=[[NSLocale alloc] initWithLocaleIdentifier:@"sv_SE"];
    
    NSArray *sorted=[strings sortedArrayUsingComparator:^(NSString *first, NSString *second) {
        return [first compare:second
                      options:0
                        range:NSMakeRange(0, [first length])
                       locale:locale];
    }];
    
    for (NSString *s in sorted) { NSLog(@"%@", s); }
    

    The output is:

    2012-04-10 08:08:18.139 Untitled[32416:707] as
    2012-04-10 08:08:18.140 Untitled[32416:707] br
    2012-04-10 08:08:18.141 Untitled[32416:707] ol
    2012-04-10 08:08:18.142 Untitled[32416:707] st
    2012-04-10 08:08:18.142 Untitled[32416:707] år
    2012-04-10 08:08:18.143 Untitled[32416:707] ög
    2012-04-10 08:08:18.143 Untitled[32416:707] ös
    
    0 讨论(0)
提交回复
热议问题