不按字母顺序对数组进行排序,而是使用字符串前缀参数



初始阵列

{
    "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循环,但我想要一些简单的解决方案来解析它

谢谢。

示例代码(根据行的第一个字排序):

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
    }
}];

您可以使用- (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) ;

最新更新