0

我有 3 个字符串。

NSString *hour1 = @"10:00";
NSString *hour2 = @"6:00";
NSString *hour3 = @"9:00";

如何检查哪个字符串具有更大的值?-> 10:00 > 9:00 > 6:00

提前致谢!

4

3 回答 3

3

将字符串添加到数组中,

NSString *hour1 = @"10:00";
NSString *hour2 = @"6:00";
NSString *hour3 = @"9:00";

NSArray *hours = [NSArray arrayWithObjects:hour1, hour2, hour3, nil];

然后对数组进行排序,

NSArray *result = [hours sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2){
    return ([obj1 compare:obj2 options:NSNumericSearch] == NSOrderedAscending);
}];
于 2012-05-17T06:30:52.673 回答
1
NSString *hour1 = @"10:00";
NSString *hour2 = @"6:00";
NSString *hour3 = @"9:00";

// Convert the hours over to int's such as 1000, 600, and 900.
int hour1AsInt = [[hour1 stringByReplacingOccurrencesOfString:@":" withString:@""] intValue];
int hour2AsInt = [[hour2 stringByReplacingOccurrencesOfString:@":" withString:@""] intValue];
int hour3AsInt = [[hour3 stringByReplacingOccurrencesOfString:@":" withString:@""] intValue];

// Make the comparison's...  This could be more efficient but works well and is easy to follow:
if (hour1AsInt > hour2AsInt) {
    if (hour1AsInt > hour3AsInt) {
        NSLog(@"Hour 1 is biggest");
        return;
    }
}

if (hour2AsInt > hour1AsInt) {
    if (hour2AsInt > hour3AsInt) {
        NSLog(@"Hour 2 is biggest");
        return;
    }
}

if (hour3AsInt > hour1AsInt) {
    if (hour3AsInt > hour2AsInt) {
        NSLog(@"Hour 3 is biggest");
        return;
    }
}
于 2012-05-17T06:30:09.513 回答
0

您应该能够使用localizedStandardCompare:

NSLog(@"%ld",[hour1 localizedStandardCompare:hour2]);
于 2012-05-17T06:30:56.947 回答