I'm implementing some code for my college and I have to sort two classes by its name. So, I started using Java's compareTo for Strings, but it wasn't doing it correctly. For example, I have these two names TEST-6 and TEST-10. But, the result was TEST-10 ahead of TEST-6.
I've searched and got this solution:
private int compare(String o1, String o2) {
return extractInt(o1) - extractInt(o2);
}
private int extractInt(String s) {
String num = s.replaceAll("\\D", "");
// return 0 if no digits found
return num.isEmpty() ? 0 : Integer.parseInt(num);
}
But my strings could assume any form. And when I tried this test: TEST-6 and TEST10) the result was TEST-6 ahead of TEST10, but what I expect is TEST10 then TEST-6.
The expected result should be normal string comparison, but comparing the full number when it is needed. So if substrings before numbers are equal, the number is compared, if not, keep string comparison. Or something like this:
TE
TES-100
TEST-1
TEST-6
TESTT-0
TEXT-2
109
a1b2c3d4?109last? Since the non-number portion is an empty string, shouldn't it be the first?compareTocould compare the two Strings that come before the digits (if a string does not have any digits then it takes the whole string for comparison). So:a= "foo1bar"andb="foo2"would result into"foo"being compared with"foo". When the two strings are already ordered now, then fine, but when they are equal (like"foo=foo") then you compare their digits1 comparedTo 2-this will result infoo1barbeing beforefoo2.. and so on, you have to compare and convert/compare all substrings until you get an order.