Reputation: 956
I am comparing two numeric string values like below
String version1 = "01.00.00"
String version2 = "01.01.00"
if (version2.compareTo(version1) >= 0) { //false
}
but this is failing when I have
String version1 = "01.99.00"
String version2 = "01.100.00"
if (version2.compareTo(version1) >= 0) { //true
}
even though "01.100.00"
greater than "01.99.00"
. Any better approach compare these two string and determine if version2 is greater than version1
Upvotes: 1
Views: 54
Reputation: 5455
You need to interpret the strings as numbers and compare these. If your strings follow this pattern - strings of digits separated by periods - you could do this cheaply using something like this:
int num1 = Integer.parseInt(version1.replace(".", ""));
int num2 = Integer.parseInt(version2.replace(".", ""));
if(num2 >= num1) {...}
Upvotes: 0
Reputation: 79620
You can use the following custom Comparator
:
class MyComparator implements Comparator<String> {
@Override
public int compare(String s1, String s2) {
int compVal;
int s1index1 = s1.indexOf(".");
String s1part1 = s1.substring(0, s1index1);
String s1part2 = s1.substring(s1index1 + 1, s1.lastIndexOf("."));
String s1part3 = s1.substring(s1.lastIndexOf(".") + 1);
int s2index1 = s2.indexOf(".");
String s2part1 = s2.substring(0, s2index1);
String s2part2 = s2.substring(s2index1 + 1, s2.lastIndexOf("."));
String s2part3 = s2.substring(s2.lastIndexOf(".") + 1);
compVal = Integer.compare(Integer.parseInt(s1part1), Integer.parseInt(s2part1));
if (compVal == 0) {
compVal = Integer.compare(Integer.parseInt(s1part2), Integer.parseInt(s2part2));
if (compVal == 0) {
compVal = Integer.compare(Integer.parseInt(s1part3), Integer.parseInt(s2part3));
}
}
return compVal;
}
}
Upvotes: 3