简体   繁体   English

排序nsarray最长到最短的字符串

[英]Sorting in nsarray longest to shortest string

I have a NSArray i want to sort by longest string to shortest string 我有一个NSArray我想按最长字符串到最短字符串排序

For example- 例如-

 NSArray *strings=[NSArray arrayWithObjects:@"as12332", @"ol", @"st", @"br", @"gj", @"wr", @"qwos", nil];

i want result like- 我想要类似的结果

@"as12332",@"qwos", @"ol", @"st", @"br", @"gj", @"wr". @“ as12332”,@“ qwos”,@“ ol”,@“ st”,@“ br”,@“ gj”,@“ wr”。

sort by string length. 按字符串长度排序。

You can use this code to implement what you're trying to achieve: 您可以使用以下代码来实现您要实现的目标:

NSArray *strings=[NSArray arrayWithObjects:@"as12332", @"ol", @"st", @"br", @"gj", @"wr", @"qwos", nil];
NSArray *sortedArray;
sortedArray = [strings sortedArrayUsingComparator:^NSComparisonResult(NSString *first, NSString *second)
{
    return [self compareLengthOf:first withLengthOf:second];
}];

sortedArray will contain the elements, sorted by length. sortedArray将包含按长度排序的元素。

The implementation for the comparison method is: 比较方法的实现是:

    - (NSComparisonResult)compareLengthOf:(NSString *)firstStr withLengthOf:(NSString *)secondStr
{
    if ([firstStr length] > [secondStr length])
        return NSOrderedAscending;
    else if ([firstStr length] < [secondStr length])
        return NSOrderedDescending;
    else
        return NSOrderedSame;
}

You can add more logic to the comparisson method, if you would like to have a secondary sort based on alphabetical order, for example. 例如,如果您希望基于字母顺序进行二级排序,则可以向比较方法添加更多逻辑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM