Advertisement
infogulch

Untitled

Apr 23rd, 2012
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.76 KB | None | 0 0
  1. class NaturalComparator implements Comparator<File> {
  2.     public int compare(File f1, File f2) {
  3.         String[] s1 = f1.getName().split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)"); // split *between* the transition from digits to non-digits & vica-versa
  4.         String[] s2 = f2.getName().split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)");
  5.         int c = 0;
  6.         for (int i = 0; i < s1.length && i < s2.length; i++)
  7.             try {
  8.                 c = new Long(s1[i]).compareTo(Long.parseLong(s2[i]));
  9.             }
  10.             catch (NumberFormatException nfe) {
  11.                 c = s1[i].compareTo(s2[i]);
  12.             }
  13.             finally {
  14.                 if (c != 0)
  15.                     return c;
  16.             }
  17.         return s1.length > s2.length ? 1 : 0;
  18.     }
  19. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement