Short game > Ballflight / Target", "Mental > I do (behavior/skills - how) > E-6ren">
gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 03:02:34 24 4
gpt4 key购买 nike

初始数组

{
"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
}

}];

关于ios - 不是按字母顺序而是使用字符串前缀参数对数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23150191/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com