我有这样的字符串集。
1 Wednesday, 3 Monday, 1 2 Tuesday
现在我需要只考虑字母来排序这些。结果将是
3 Monday, 1 2 Tuesday, 1 Wednesday
通过考虑子串(星期三,星期一,星期二)对字符串进行排序,因此得到了结果。我怎么能这样做?
答案 0 :(得分:0)
使用compareOptions,在选项中删除kCFCompareNumerically。
参见下一个网址: Sorting Strings
或试试这个:
#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;
}
答案 1 :(得分: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星期三” )强>
答案 2 :(得分: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];