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 = @\
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 + "', ");
}
}
}