Comparing version numbers

后端 未结 8 1597
予麋鹿
予麋鹿 2020-12-11 11:39

Some time ago, I read that comparing version numbers can be done using the following code snippet:

NSString *vesrion_1 = @\"1.2.1\";
NSString *version_2 = @\         


        
8条回答
  •  生来不讨喜
    2020-12-11 12:19

    In Java you could use the following code snippet to compare versions. If one version number is shorter then the other we normalize it with zeros.

    import java.util.Arrays;
    import java.util.Comparator;
    
    public class FreePlay {
    
        static String[] versions = {"1.5.3.2", "2.3.4", "1.0.3.4", "10.10.1.1", "1.0.2.5", "2.3.4"};
        /**
         * @param args
         */
        public static void main(String[] args) {
            System.out.println("Unsorted versions");
            for (String s: versions) {
                System.out.print("'" + s + "', ");
            }
    
            System.out.println("\nSorted versions");
    
            Arrays.sort(versions, new Comparator() {
    
                @Override
                public int compare(String o1, String o2) {
                    String[] firstVersions = o1.split("\\.");
                    String[] secondVersions = o2.split("\\.");
                    int length = Math.max(firstVersions.length, secondVersions.length);
                    for(int i = 0; i < length; i++) {
                        // normalize the length. If one part is short, we normalize it with zero
                        int firstVersion = i < firstVersions.length ? Integer.parseInt(firstVersions[i]) : 0;
                        int secondVersion = i < secondVersions.length ? Integer.parseInt(secondVersions[i]) : 0;
                        if(firstVersion < secondVersion)
                            return -1;
                        if(firstVersion > secondVersion)
                            return 1;
                    }
                    return 0;
                }});
    
            for (String s: versions) {
                System.out.print("'" + s + "', ");
            }
        }
    
    }
    

提交回复
热议问题