首先按NSString字母阿拉伯语排序NSArray

时间:2015-01-13 05:41:40

标签: ios objective-c cocoa-touch sorting

如何按字母顺序对包含字符串的NSArray进行排序,但我希望阿拉伯字符串优先于英语并放在排序数组之上

2 个答案:

答案 0 :(得分:1)

我以同样的方式完成了它:)

    -(NSArray*)arabicFirstSortedArray:(NSArray*)arr {    

    static NSStringCompareOptions comparisonOptions = NSCaseInsensitiveSearch | NSNumericSearch |
    NSWidthInsensitiveSearch | NSForcedOrderingSearch;

    NSLocale *locale = [NSLocale localeWithLocaleIdentifier:@"ar"];

    NSArray *sortedArray = [arr sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {

        NSRange string1Range = NSMakeRange(0, [obj1 length]);

        return [obj1 compare:obj2 options:comparisonOptions range:string1Range locale:locale];
    }];

    return sortedArray;
}

这是另一种使阿拉伯字符串位于顶部的方法,但保留排序

-(NSArray*)arabicFirstSortedArray:(NSArray*)arr {
NSArray *sortedArray = [arr sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {

    BOOL isFirstArabic = [self isArabicString:obj1];
    BOOL isSecondArabic = [self isArabicString:obj2];

    if (isFirstArabic == isSecondArabic) {
        return NSOrderedSame;
    }
    else if(isFirstArabic){
        return NSOrderedAscending;
    }
    else{
        return NSOrderedDescending;
    }
}];

return sortedArray;
}

-(BOOL)isArabicString:(NSString*)str {

NSString *isoLangCode = (__bridge_transfer NSString*)CFStringTokenizerCopyBestStringLanguage((__bridge CFStringRef)str, CFRangeMake(0, str.length));

if([isoLangCode isEqualToString:@"ar"]){
    return YES;
}
else{
    return NO;
}
}

答案 1 :(得分:0)

您可以使用compare:options:range:locale:并明确指定阿拉伯语语言环境,使其正常工作,如下所示:

NSArray *strings=[NSArray arrayWithObjects:@"as", @"ol", @"st", nil]; // also contain 
NSLocale *locale=[[NSLocale alloc] initWithLocaleIdentifier:@"ar_BH"];

NSArray *sorted=[strings sortedArrayUsingComparator:^(NSString *first, NSString *second) {
    return [second compare:first
                  options:0
                    range:NSMakeRange(0, [second length])
                   locale:locale];
}];

for (NSString *s in sorted) { NSLog(@"%@", s); }