代码之家  ›  专栏  ›  技术社区  ›  Manjunath

排序Unicode字符串

  •  1
  • Manjunath  · 技术社区  · 15 年前

    3 回复  |  直到 15 年前
        1
  •  3
  •   Akusete    15 年前

    Objective-C(NSString*)中的所有字符串都是unicode字符串。它们是unicode字符序列(与编码字节序列相反)。可以使用NSArray提供的方法对字符串数组进行排序。

    NSArray* myArray = [NSArray arrayWithObjects:@"はじめまして", @"русский язык", @"คนอ้วน ๆ", nil];
    
    NSArray* mySortedArray = [myArray sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
    

    这将按unicode顺序对字符串进行排序,如果您有其他排序条件,则提供自定义排序选择器或详细说明您的问题。

        2
  •  1
  •   Kendall Helmstetter Gelner    15 年前

    如果要使用排序描述符进行排序,也可以按如下方式进行排序:

    NSSortDescriptor *sorter = [NSSortDescriptor descriptorWithKey:@"description" ascending:YES];
    NSArray* mySortedArray = [myArray sortedArrayUsingDescriptors:[NSArray arrayWithObject:sorter]];
    

    使用NSSortDescriptor路径的优点是可以有多个排序描述符,或者可以选择使用降序排序。

        3
  •  1
  •   Manjunath    15 年前

    谢谢你帮我。

    localizedCaseInsensitiveCompare

    NSComparisonResult sortLocationsForStr(NSString* str1, NSString* str2, void *context)
    {
        return [str1 localizedCaseInsensitiveCompare:str2];
    }
    
    [myArrayToSort sortUsingFunction:sortLocationsForStr context:nil];