sorting - Comparing strings with alphanumerics - Java -
i'm implementing java
class compares strings alphanumerics. example, "woot", "w00t"
returned "w00t", "woot"
. class implements comparator
interface:
class mycomparator implements comparator<charsequence> { @override public int compare (charsequence s1, charsequence s2) { pattern pattern = pattern.compile("(\\d*)(\\d*)"); matcher m1 = pattern.matcher(s1); matcher m2 = pattern.matcher(s2); while (m1.find() && m2.find()) { int nondigitcompare = m1.group(1).compareto(m2.group(1)); if (0 != nondigitcompare) { return nondigitcompare; } if (m1.group(2).isempty()) { return m2.group(2).isempty() ? 0 : -1; } else if (m2.group(2).isempty()) { return 1; } biginteger n1 = new biginteger(m1.group(2)); biginteger n2 = new biginteger(m2.group(2)); int numbercompare = n1.compareto(n2); if (0 != numbercompare) { return numbercompare; } } return m1.hitend() && m2.hitend() ? 0 : m1.hitend() ? -1 : 1; } }
for cases above code works fine. however, following string[] arguments
fails:
string[] arguments = {"p6.py", "p0007.py", "pa", "2016-05-02", "p.py", ".py", "10.20.30.40", "p9", "b"};
it outputs "10.20.30.40, 2016-05-02, .py, b, p6.py, p0007.py, p9 ,p.py , pa"
instead of ".py, 10.20.30.40, 2016-05-02, b, p.py, p6.py, p007.py, p9, pa"
.
what's wrong compare
method?
Comments
Post a Comment