开发者

Sorting Unicode strings

开发者 https://www.devze.com 2023-01-10 00:30 出处:网络
How do I sort Unicode (foreign) strings in my iPhone applica开发者_开发知识库tion?All strings in Objective-C (NSString*) are unicode strings. They are sequences of unicode characters (as opposed to se

How do I sort Unicode (foreign) strings in my iPhone applica开发者_开发知识库tion?


All strings in Objective-C (NSString*) are unicode strings. They are sequences of unicode characters (as opposed to sequences of encoded bytes). You can sort an array of strings using the methods provided by NSArray.

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

NSArray* mySortedArray = [myArray sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];

This will sort the strings by their unicode order, if you have some other sorting condition then provide a custom sorting selector or elaborate on your question.


If you want to sort using sort descriptors, you can also sort like so:

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

"description" works OK as a key for NSString values, since description is documented to return itself.

The advantage of going the NSSortDescriptor route is that you can have more than one sort descriptor, or you can select to use a descending sort instead.


Thanks for helping me.

localizedCaseInsensitiveCompare

this API will do the sorting with respect to localization. Otherwise strings of different languages will be treated as a unicode strings and comparison fails.

Here is the solution:

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

[myArrayToSort sortUsingFunction:sortLocationsForStr context:nil];
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号