NSString运算符(如果字符串比另一个字符串大)

时间:2012-05-17 06:17:37

标签: objective-c ios4 nsstring operators

我有3个字符串。

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

如何查看哪个字符串值更大? - > 10:00> 9:00> 6:00

提前致谢!

3 个答案:

答案 0 :(得分: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);
}];

答案 1 :(得分: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;
    }
}

答案 2 :(得分:0)

您应该可以使用localizedStandardCompare:

NSLog(@"%ld",[hour1 localizedStandardCompare:hour2]);