0

I have set of strings like this.

1 Wednesday, 3 Monday, 1 2 Tuesday

Now I need to sort these considering only letters. The results will be

3 Monday, 1 2 Tuesday, 1 Wednesday

The strings are sorted by considering substrings (Wednesday, Monday, Tuesday) so I got the result. How I can do that ?

4

3 回答 3

0

使用 compareOptions,去掉选项中的 kCFCompareNumerically。

请参阅下一个 url: 排序字符串

或试试这个:

#import <Foundation/Foundation.h>

int main (int argc, const char * argv[]) {

@autoreleasepool {

    NSArray *stringsArray = [NSArray arrayWithObjects:
                             @"string 1",
                             @"String 21",
                             @"string 12",
                             @"String 11",
                             @"String 02", nil];
    static NSStringCompareOptions comparisonOptions = NSCaseInsensitiveSearch |
    NSWidthInsensitiveSearch | NSForcedOrderingSearch;
    NSLocale *currentLocale = [NSLocale currentLocale];
    NSComparator finderSort = ^(id string1, id string2) {
        NSRange string1Range = NSMakeRange(0, [string1 length]);
        return [string1 compare:string2 options:comparisonOptions range:string1Range locale:currentLocale];
    };

    NSArray* sortedArray = [stringsArray sortedArrayUsingComparator:finderSort];
    NSLog(@"finderSort: %@", sortedArray);        
    }
    return 0;
}
于 2013-04-19T07:55:01.840 回答
0

或者,如果您要排序的字符串始终是最后一个字符串(并且总是有一个最后一个字符串),您可以编写一个对最后一个字符串进行排序的比较器:

NSComparator lastStringSort = ^(id string1, id string2)
{
    NSArray* string1Components = [string1 componentsSeparatedByString:@" "];
    NSArray* string2Components = [string2 componentsSeparatedByString:@" "];
    return [[string1Components lastObject] compareToString:[string2Components lastObject]];
};

NSArray* sortedArray = [stringsArray sortedArrayUsingComparator:lastStringSort];
于 2013-04-19T08:28:13.313 回答
0

尝试

NSArray *array = @[@"1 Wednesday",@"3 Monday",@"1 2 Tuesday"];

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"EEEEE"];

NSArray *sortedArray = [array sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
    NSCharacterSet *validCharacterSet = [NSCharacterSet letterCharacterSet];
    NSCharacterSet *unwantedCharecterSet = [validCharacterSet invertedSet];
    NSString *string1 = [(NSString *)obj1 stringByTrimmingCharactersInSet:unwantedCharecterSet];
    NSString *string2 = [(NSString *)obj2 stringByTrimmingCharactersInSet:unwantedCharecterSet];

    NSDate *date1 = [dateFormatter dateFromString:string1];
    NSDate *date2 = [dateFormatter dateFromString:string2];

    return [date1 compare:date2];

}];

(“3 星期一”、“1 2 星期二”、“1 星期三”)

于 2013-04-19T08:06:55.893 回答