开发者

sorting NSArray of NSStrings by match occurrence

开发者 https://www.devze.com 2023-02-11 01:51 出处:网络
How can I sort NSArray by search pattern matching? So if for example I have a search pattern equal \'xd\' and an array of values:

How can I sort NSArray by search pattern matching? So if for example I have a search pattern equal 'xd' and an array of values:

axd
bxd
xdd
gtxd
xdc

how can I get the output like below:

xdc 开发者_如何学JAVA
xdd 
axd 
bxd 
gtxd

Thank you in advance.


Use NSArray's sortedArrayUsingFunction: with a function that orders first by the position of the search term, then by the strings' natural ordering.

NSInteger sorter(id arg1, id arg2, void *context)
{
    NSString *searchTerm = (NSString *)context;

    NSRange range1 = [arg1 rangeOfString:searchTerm];
    NSRange range2 = [arg2 rangeOfString:searchTerm];

    if (range1.location < range2.location)
        return NSOrderedAscending;
    if (range1.location > range2.location)
        return NSOrderedDescending;

    return [arg1 compare:arg2];
}

NSArray *array = [NSArray arrayWithObjects:@"axd", @"bxd", @"xdd", @"gtxd", @"xdc", nil];
NSArray *sortedArray = [array sortedArrayUsingFunction:sorter context:@"xd"];

This prints:

2011-02-15 01:33:49.642 GreatApp[78849:a0f] (
    xdc,
    xdd,
    axd,
    bxd,
    gtxd
)


You can use NSArray's sortedArrayUsingFunction:context: method:

NSInteger occurenceSort(NSString* s1, NSString* s2, void *context)
{
    NSRange range1 = [s1 rangeOfString:(NSString*)context];
    NSRange range2 = [s2 rangeOfString:(NSString*)context];

    if (range1.location < range2.location)
        return NSOrderedAscending;
    else if (range1.location > range2.location)
        return NSOrderedDescending;

    return NSOrderedSame;
}

...
NSString *stringToSearch = @"xd";
NSArray *sorterArray = [yourArray sortedArrayUsingFunction:occurenceSort context:stringToSearch];
0

精彩评论

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