本文介绍了如何从包含以下格式的字符串的NSArray获取排序的NSArray"2.0.1","2.0.09","2.0.5".的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何从包含具有两个小数点的数字字符串的NSArray中获取排序后的NSArray.谁能在这方面帮助我.预先感谢.
how to get the sorted NSArray from the NSArray that contains number string with two decimal points. Can anyone help me in this regard. Thanks in advance.
推荐答案
这应该为您解决问题:
NSNumberFormatter *nf = [[NSNumberFormatter alloc] init];
NSArray *sortedArray = [unsortedArray sortedArrayUsingComparator:^(id obj1, id obj2) {
if ([obj1 isKindOfClass:[NSString class]] && [obj2 isKindOfClass:[NSString class]]) {
NSArray *obj1Components = [(NSString *)obj1 componentsSeparatedByString:@"."];
NSArray *obj2Components = [(NSString *)obj2 componentsSeparatedByString:@"."];
int highestCount = obj1Components.count;
if (obj2Components.count > highestCount) {
highestCount = obj2Components.count;
}
for (int i = 0; i < highestCount; i++) {
// If the component does not exist, just make it 0
NSNumber *num1 = [NSNumber numberWithInt:0];
if (i < obj1Components.count) {
num1 = [nf numberFromString:[obj1Components objectAtIndex:i]];
}
NSNumber *num2 = [NSNumber numberWithInt:0];
if (i < obj2Components.count) {
num2 = [nf numberFromString:[obj2Components objectAtIndex:i]];
}
int int1 = [num1 intValue];
int int2 = [num2 intValue];
if (int1 > int2) {
return NSOrderedDescending;
} else if (int2 > int1) {
return NSOrderedAscending;
}
}
// If we reach here, they're the same.
return NSOrderedSame;
} else {
// They're not strings, so just say they're the same
return NSOrderedSame;
}
}];
[nf release];
它将需要类似["1.4.2","0.4.9","1","3.3.3.3.3"]的内容,并将其转换为["0.4.9","1","1.4.2," 3.3.3.3.3]
It'll take something like ["1.4.2", "0.4.9", "1", "3.3.3.3.3"] and turn it into ["0.4.9", "1", "1.4.2", "3.3.3.3.3"]
这篇关于如何从包含以下格式的字符串的NSArray获取排序的NSArray"2.0.1","2.0.09","2.0.5".的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!