按字母顺序排序数组但使用字符串前缀参数

时间:2014-04-18 08:18:43

标签: ios sorting

初始数组

{
    "Golf > Short game > Ballflight / Target",
    "Mental > I do (behavior/skills - how) > Energy / Emotions",
    "Fitness > Endurance",
    "Fitness > Flexibility",
    "Golf > Long game",
    "Golf > Long game > Approach from fairway",
    "Golf > Practice Game",
}

我想将上面的数组从golffitnessmental开始排序。
所以结果数组如下所示

{
    "Golf > Short game > Ballflight / Target",
    "Golf > Long game",
    "Golf > Long game > Approach from fairway",
    "Golf > Practice Game",
    "Fitness > Endurance",
    "Fitness > Flexibility",
    "Mental > I do (behavior/skills - how) > Energy / Emotions",
}

请指导我。

我尝试使用for循环,但我想要一些简单的解决方案来解析它。

谢谢。

2 个答案:

答案 0 :(得分:1)

示例代码(基于行的第一个单词排序):

NSMutableArray *myArray = [@[
    @"Golf > Short game > Ballflight / Target",
    @"Mental > I do (behavior/skills - how) > Energy / Emotions",
    @"Fitness > Endurance",
    @"Fitness > Flexibility",
    @"Golf > Long game",
    @"Golf > Long game > Approach from fairway",
    @"Golf > Practice Game",
    ] mutableCopy];

NSDictionary *scores = @{@"Golf":@1, @"Fitness":@2, @"Mental":@3};

[myArray sortUsingComparator:^NSComparisonResult(NSString *str1, NSString *str2) {

    // first word (can be refined checking for better word break chars)
    NSString *prefix1;
    NSRange rangeUntilSpace1 = [str1 rangeOfString:@" "];
    if (rangeUntilSpace1.location != NSNotFound)
        prefix1 = [str1 substringToIndex:rangeUntilSpace1.location];
    else
        prefix1 = str1;

    NSString *prefix2;
    NSRange rangeUntilSpace2 = [str2 rangeOfString:@" "];
    if (rangeUntilSpace2.location != NSNotFound)
        prefix2 = [str2 substringToIndex:rangeUntilSpace2.location];
    else
        prefix2 = str2;

    // scores (taken from the previous dictionary)
    NSInteger score1 = [scores[prefix1] intValue];
    NSInteger score2 = [scores[prefix2] intValue];

    if (score1 && score2) {

        return score1 > score2 ? NSOrderedDescending : NSOrderedAscending;
    } else if (score1) {

        return NSOrderedAscending;  // if not in scores dictionary, put down
    } else {

        return NSOrderedDescending; // if not in scores dictionary, put down
    }

}];

答案 1 :(得分:0)

您可以使用- (NSArray *)sortedArrayUsingComparator:(NSComparator)cmptr

这是一个例子。

NSArray *array = @[@"G", @"M", @"F"] ;
array = [array sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
    NSString *s1 = obj1 ;
    NSString *s2 = obj2 ;
    unichar u1 = [s1 characterAtIndex:0] ;
    unichar u2 = [s2 characterAtIndex:0] ;
    if (u1 == u2) {
        return [s1 compare:s2] ;
    } else {
        if (u1 == 'G') {
            return NSOrderedAscending ;
        } else if (u1 == 'M') {
            return NSOrderedDescending ;
        } else {
            return u2 == 'G' ? NSOrderedDescending : NSOrderedAscending ;
        }
    }
}] ;
NSLog(@"%@", array) ;