简体   繁体   English

按字符串值对字符串的NSMutableArray进行排序

[英]Sorting an NSMutableArray of strings by string value

I get an array of strings with the following strings, there is a certain patern to the strings 我得到一个包含以下字符串的字符串数组,字符串有一定的样式

str1 str51 str3 str4 str10 str39 str31 str191 str1 str51 str3 str4 str10 str39 str31 str191

Every string starts with 'str' and has a number appended onto the end of it. 每个字符串均以“ str”开头,并在其末尾附加一个数字。

Is there a neath way to sort the array so it lists the strings in order of value 有没有一种很好的方法可以对数组进行排序,以便按值的顺序列出字符串

str1 str3 str4 str10 str31 str39 str51 str191 str1 str3 str4 str10 str31 str39 str51 str191

I can see a way to do it by writing some recursive function that will 我可以看到通过写一些递归函数来做到这一点的方法

NSString * firstString = [[strArray objectAtIndex:i].substringFromIndex:3];
NSString * secondString = [[strArray objectAtIndex:i+1].substringFromIndex:3];

if ([firstString intValue] < [secondString intValue])
{
    //do nothing they order is correct
}
else
{
    //swap the order of the 2 strings in the array
}

But thats very rudimentary code, Is there some mechanism in Objective-C or a nice code trick to handle this sorting better? 但这就是非常基本的代码,Objective-C中是否存在某种机制或更好的代码技巧可以更好地处理这种排序?

Many Thanks, -Code 非常感谢,-Code

If they all start with the same prefix, I believe that the default sort will handle them appropriately. 如果它们都以相同的前缀开头,我相信默认排序将适当地处理它们。 By this, I mean: 通过这个,我的意思是:

[someArray sortUsingSelector:@selector(compare:)];

If, for some reason, this isn't working, then you can use a block. 如果由于某种原因这不起作用,则可以使用一个块。 Try this: 尝试这个:

NSArray *sortedArray = [someArray sortedArrayUsingComparator:^NSComparisonResult(id a, id b) 
{
    //Default compare, to protect against cast
    if (![a isKindOfClass:[NSString class]] || ![b isKindOfClass:[NSString class]]) {
        return ([a compare:b]);
    }
    else {
        NSString *aString = (NSString*) a;
        NSString *bString = (NSString*) b;
        int aInt = [[a.substringFromIndex:3] intValue];
        int bInt = [[b.substringFromIndex:3] intValue];
        return [aInt < bInt];
    }
}];

You could sort it like this 你可以这样排序

NSArray *sortedArray = [unsortedArray sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
    NSString * str1 = [(NSString *)obj1 substringFromIndex:3];
    NSString * str2 = [(NSString *)obj2 substringFromIndex:3];
    return [str1 compare:str2 options:NSNumericSearch];
}];

You can define a comparator function with whatever behavior you want. 您可以根据需要的行为定义比较器函数。 The one below will emulate the behavior of Finder in Mac OS, ignoring case and respecting numbers occurring at the end of strings. 下面的示例将模仿Mac OS中Finder的行为,忽略大小写并注意出现在字符串末尾的数字。 The order will be dependent on the provided locale, though, so if you want the results to be absolutely consistent, you should pick a locale and hard-code it. 但是,顺序将取决于提供的语言环境,因此,如果希望结果绝对一致,则应选择一个语言环境并对其进行硬编码。

int finderSortWithLocale(id string1, id string2, void *locale)
{
    static NSStringCompareOptions comparisonOptions =
        NSCaseInsensitiveSearch | NSNumericSearch |
        NSWidthInsensitiveSearch | NSForcedOrderingSearch;

    NSRange string1Range = NSMakeRange(0, [string1 length]);

    return [string1 compare:string2
                    options:comparisonOptions
                    range:string1Range
                    locale:(__bridge NSLocale *)locale];
}

You should definitely read the documentation on each of those options to ensure it does what you're looking for. 您绝对应该阅读所有这些选项的文档,以确保它可以满足您的需求。

To use such a comparator to efficiently sort a string array, use the sortedArrayUsingFunction:context: method: 要使用这种比较器对字符串数组进行有效排序,请使用sortedArrayUsingFunction:context:方法:

NSArray *sortedArray = [stringsArray sortedArrayUsingFunction:finderSortWithLocale context:(__bridge void *)[NSLocale currentLocale]];

Create a NSSortDescriptor and sort the array on the key: "description". 创建一个NSSortDescriptor并对键“ description”上的数组进行排序。 Like This: 像这样:

NSMutableArray *array = [NSMutableArray arrayWithCapacity:0]; //Your Array of NSStrings
NSSortDescriptor *descriptor = [NSSortDescriptor sortDescriptorWithKey:@"description" ascending:YES];
array = [array sortedArrayUsingDescriptors:@[descriptor]];
NSSortDescriptor *sortByName = [NSSortDescriptor sortDescriptorWithKey:@"datetime"
                                                             ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortByName];
NSArray *sortedArray = [myArrayNonsort sortedArrayUsingDescriptors:sortDescriptors];

sortedArray = [anArray sortedArrayUsingSelector: @selector(localizedCaseInsensitiveCompare:)]; sortedArray = [anArray sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare :)]];

input:anArray output:sortedArray 输入:anArray输出:sortedArray

refer the docs 参考文档

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

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