This should work from 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);
}
See here 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 way out:
-3
1
-3
0
Works according to the interface principle java.util.Comparator
. Where:
- A zero return means equal strings.
- A negative number is when the first precedes the second.
- A positive number is when the first 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 for creating several temporary intermediate objects to add zeros. An optimization that already creates all the necessary zeros once is possible. It is also possible to proceed directly to the 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.
It depends on how much you trust the format you are in. Always 2 characters, always have a 0 on the left if you only have one significant digit? If not, never have 0 before? If it can be different size, it has a maximum?
– Maniero
@bigown the only confidence I have is that both will always be a numerical type and no floating point. Now the number of houses can be 1 or 7.
– user28595
I can put the number of fixed houses in the string, if this facilitates resolution. What I want is to avoid creating temporary int variable or parse and then go back to string again.
– user28595
Not so much, knowing a maximum can be useful. It is more important to know if you can have 0 on the left, if you always will, or never will. Whether you can have it or not, complicates it, but you can do it.
– Maniero