比较位数和数字大小
public class test {
public static int compareVersion(String version_old, String version_new) throws Exception {
if (version_old == null || version_new == null) {
throw new Exception("compareVersion error:illegal params.");
}
String[] versionArray1 = version_old.split("\\.");//注意此处为正则匹配,不能用".";
String[] versionArray2 = version_new.split("\\.");
int idx = 0;
//取最小长度值
int minLength = Math.min(versionArray1.length, versionArray2.length);
int diff = 0;
//比较相同位数的值的大小,如果比较出来了就直接返回
while (idx < minLength
&& (diff = versionArray2[idx].length() - versionArray1[idx].length()) == 0//先比较长度
&& (diff = versionArray2[idx].compareTo(versionArray1[idx])) == 0) {//再比较字符
++idx;
}
//如果已经分出大小,则直接返回,如果未分出大小,则再比较位数,有子版本的为大;
diff = (diff != 0) ? diff : versionArray2.length - versionArray1.length;
return diff;
}
public static void main(String[] args) throws Exception {
System.out.println(compareVersion("1.1.1","1.1.1a"));
}
}