如何比较两个版本号字符串?
例如:3.1.1和3.1.2.5.4
现在我需要找出3.1.2.5.4是否高于3.1.1但我不知道如何做到这一点。 有人能帮助我吗?
提前致谢!
答案 0 :(得分:9)
示例代码:
NSString* v1 = @"3.1.1";
NSString* v2 = @"3.1.2.5.4";
if ([v1 compare:v2 options:NSNumericSearch] == NSOrderedDescending) {
NSLog(@"%@ is greater than %@",v1,v2);
}
来自Comparing and sorting strings的Apple文档。
答案 1 :(得分:2)
是的,您可以比较各个版本,请参阅以下代码:
public class Comparision {
string ver1, ver2;
public static void main(String args[]){
string ver1Split[] = ver1.split('.');
string ver2Split[] = ver2.split('.');
for (int i = 0; i < ver1Split.length; ++i) {
if (ver2Split == i) {
return ver1 + " is larger";
}
if (ver1Split[i] == ver2Split[i]) {
continue;
}
else if (ver1Split[i] > ver1Split[i]) {
return ver1 + " is larger";
}
else {
return ver2 + " is larger";
}
if (ver1Split.length != ver2Split.length) {
return ver2 + " is larger";
}
return "versions are equal";
}
}
答案 2 :(得分:0)
Objective-C:
- (BOOL)isVersion:(NSString *)arg1 higherThan:(NSString *)arg2 {
NSMutableString * v1 = arg1.mutableCopy;
NSMutableString * v2 = arg2.mutableCopy;
NSMutableArray * parts1 = [v1 componentsSeparatedByString:@"."].mutableCopy;
NSMutableArray * parts2 = [v2 componentsSeparatedByString:@"."].mutableCopy;
if (parts1.count > parts2.count) {
NSInteger diff = parts1.count - parts2.count;
for (NSInteger i = diff; i<parts1.count; i++) {
[v2 appendString:@".0"];
}
} else if (parts1.count < parts2.count){
NSInteger diff = parts2.count - parts1.count;
for (NSInteger i = diff; i<parts2.count; i++) {
[v1 appendString:@".0"];
}
}
parts1 = [v1 componentsSeparatedByString:@"."].mutableCopy;
parts2 = [v2 componentsSeparatedByString:@"."].mutableCopy;
NSInteger j = 0;
for (NSString * num1 in parts1) {
NSString * num2 = parts2[j];
if(num1.integerValue > num2.integerValue){
//break;
return YES;
} else if (num1.integerValue < num2.integerValue) {
//break;
return NO;
} else {
// ==
}
j++;
}
return NO;
}
单元测试:
- (void)test_isHigherFunc {
XCTAssert([self isVersion:@"4.1.2.1" higherThan:@"4.1.2.0"]);
XCTAssertFalse([self isVersion:@"4.1.2.0" higherThan:@"4.1.2.0"]);
XCTAssert([self isVersion:@"4.1.2.0" higherThan:@"4.1.1.0"]);
XCTAssertFalse([self isVersion:@"3.1.2.0" higherThan:@"4.1.1.0"]);
XCTAssertFalse([self isVersion:@"4.2.2.0" higherThan:@"4.3.1.0"]);
XCTAssert([self isVersion:@"5.2" higherThan:@"4.3.1.0"]);
XCTAssertFalse([self isVersion:@"6.2" higherThan:@"7.3.1.0"]);
XCTAssert([self isVersion:@"6.2" higherThan:@"5"]);
XCTAssert([self isVersion:@"6.2.0" higherThan:@"5.9"]);
XCTAssert([self isVersion:@"1.1.1.1.1.1.1.1" higherThan:@"1.1.1.1.1.1.1.0"]);
XCTAssert([self isVersion:@"2.0" higherThan:@"1"]);
}