gpt4 book ai didi

objective-c - 当字符串包含 åäö 时,如何按字母顺序对字符串数组进行排序?

转载 作者:太空狗 更新时间:2023-10-30 03:36:02 25 4
gpt4 key购买 nike

我正在 xcode4.3/Objective-C 中构建应用程序,在尝试对 NSMutableArray 进行排序时遇到了问题。我将使用 sqlite 数据库中的字符串填充它。问题出现在瑞典语字符 å、ä 和 ö 上。

有序数组应如下所示:as, br, ol, st, år, ög, ös。

但是当我使用选择器时,比较顺序是这样的:as, år, br, ol, ög, ös, st。

当我使用 localizedCompare 时,顺序更改为:as、år、br、ög、ol、ös、st。

根据较旧的线程,localizedCompare 应该是解决方案,但我无法使其正常工作。如果我使用终端访问 sqlite 数据库并键入 ORDER,我将得到正确的结果。我的问题可能与 xcode 或 iphone 模拟器中的某些设置有关,因为它们都显示不正确的顺序?或者 localizedCompare 是错误的方法吗?只要能完成工作,我会很乐意接受任何解决方法。谢谢。

最佳答案

您可以通过使用 compare:options:range:locale: 并明确指定瑞典语言环境来使其工作,如下所示:

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); }

输出是:

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

关于objective-c - 当字符串包含 åäö 时,如何按字母顺序对字符串数组进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9912411/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com