Is it possible to compare numeric values in strings without doing cast for type Number?

5

I have two numeric values that are retrieved in strings and I would like to know if there is a way to compare them to see which numeric value is larger but without having to convert to type Number (as Integer , Double and% with%).

Example:

String strValue01 = "50";
String strValue02 = "62";

Is there any way to compare which number is larger, without having to parse for numeric type ? I thought there might be something via ASCII values, but I have no idea how you do it, if at all possible.

    
asked by anonymous 18.09.2017 / 19:39

1 answer

4

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.

    
18.09.2017 / 19:47