This should work here:
public static int seuComparador(String a, String b) {
String c = a;
String d = b;
while (c.length() < d.length()) c = "0" + c;
while (c.length() > d.length()) d = "0" + d;
return c.compareTo(d);
}
Here's a test:
public static void main(String[] args) {
System.out.println(seuComparador("0", "3"));
System.out.println(seuComparador("10", "3"));
System.out.println(seuComparador("007", "300"));
System.out.println(seuComparador("40", "040"));
}
Here's the output:
-3
1
-3
0
It works according to the interface principle java.util.Comparator
. Where:
- A zero return means equal strings.
- A negative number is when the first one precedes the second.
- A positive number is when the first one succeeds the second.
That is, this output means that 0 is less than 3, that 10 is greater than 3, that 007 is less than 300 and that 40 is equal to 040.
See here working on ideone.
However, this code is not very efficient by creating multiple temporary intermediate objects to append zeros. An optimization that already creates all the required zeros only once is possible. You can also proceed directly to compareTo
when the sizes of String
s are equal:
public static int seuComparador(String a, String b) {
int sa = a.length();
int sb = b.length();
if (sa == sb) return a.compareTo(b);
int dif = sa > sb ? sa - sb : sb - sa;
StringBuilder pad = new StringBuilder(sa > sb ? sa : sb);
for (int i = 0; i < dif; i++) {
pad.append('0');
}
String c = sa > sb ? a : pad.append(a).toString();
String d = sa > sb ? pad.append(b).toString() : b;
return c.compareTo(d);
}
Produces the same output as the previous one. See here working on ideone.