zoukankan      html  css  js  c++  java
  • 软件版本号比较 java工具类

    这段程序主要用于比较sdk的版本号,例如 8.9.1 和8.9.0,8.9.1和8.7的比较。

    import org.apache.commons.lang3.StringUtils;
    
    import java.util.regex.Pattern;
    
    public class NumUtils {
    
       /**
         * @description 比较SDK版本号
         * @param version1
         * @param version2
         * @return
         */
        public static int compareVersion(String version1, String version2){
            if (version1 == null || version2 == null) {
            }
            version1 = version1.replaceAll("([^(\d|\.)])", "");
            version2 = version2.replaceAll("([^(\d|\.)])", "");
            String[] versionArray1 = version1.split("\.");//注意此处为正则匹配, 不能用.;
            String[] versionArray2 = version2.split("\.");
            int idx = 0;
            int minLength = Math.min(versionArray1.length, versionArray2.length);//取最小长度值
            int diff = 0;
            while (idx < minLength
                    && (diff = versionArray1[idx].length() - versionArray2[idx].length()) == 0//先比较长度
                    && (diff = versionArray1[idx].compareTo(versionArray2[idx])) == 0) {//再比较字符
                ++idx;
            }
            //如果已经分出大小,则直接返回,如果未分出大小,则再比较位数,有子版本的为大;
            diff = (diff != 0) ? diff : versionArray1.length - versionArray2.length;
            return diff;
        }
        public static void main(String[] args) {  
         System.out.println(compareVersion("6.0.0".replaceAll("([^(\d|\.)])", ""), "6.0.0") ==0);  //true
    System.out.println(compareVersion("5.6.1".replaceAll("([^(\d|\.)])", ""), "5.6.0") > 0); //true
    System.out.println(compareVersion("5.6.1".replaceAll("([^(\d|\.)])", ""), "5.6.2") > 0); //false
     } }
  • 相关阅读:
    LeetCode5 Longest Palindromic Substring
    LeetCode4 Median of Two Sorted Arrays
    LeetCode3 Longest Substring Without Repeating Characters
    LeetCode2 Add Two Numbers
    LeetCode1 Two Sum
    算法总结—深度优先搜索DFS
    c++ 设计模式9 (Abstract Factory 抽象工厂模式)
    题解 P3374 【【模板】树状数组 1】
    题解 HDU1565 【方格取数(1)】
    题解 P2431 【正妹吃月饼】
  • 原文地址:https://www.cnblogs.com/Allen-win/p/10526357.html
Copyright © 2011-2022 走看看