fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10.  
  11. public static void main (String[] args) throws java.lang.Exception
  12. {
  13. String[] array = {"string-a01","string-a20","string-a100","string-b01","string-b20","string-b100","string-c01","string-c20","string-c100"};
  14.  
  15. Arrays.sort(array, new Comparator<String>() {
  16. int firstTrailingDigit(String s) {
  17. int i = s.length();
  18. while (i > 0 && Character.isDigit(s.charAt(i - 1))) {
  19. --i;
  20. }
  21. return i;
  22. }
  23.  
  24. @Override public int compare(String a, String b) {
  25. int ftdA = firstTrailingDigit(a);
  26. int ftdB = firstTrailingDigit(b);
  27.  
  28. // Get the leading strings, and compare.
  29. String sA = a.substring(0, ftdA);
  30. String sB = b.substring(0, ftdB);
  31. int compareStrings = sA.compareTo(sB);
  32. if (compareStrings != 0) {
  33. // If they're not equal, return the result of the comparison.
  34. return compareStrings;
  35. }
  36.  
  37. // Get the trailing numbers from the strings, and compare.
  38. int iA = Integer.parseInt(a.substring(ftdA));
  39. int iB = Integer.parseInt(b.substring(ftdB));
  40. return Integer.compare(iA, iB);
  41. }
  42. });
  43.  
  44. System.out.println(Arrays.toString(array));
  45. }
  46. }
Success #stdin #stdout 0.04s 320576KB
stdin
Standard input is empty
stdout
[string-a01, string-a20, string-a100, string-b01, string-b20, string-b100, string-c01, string-c20, string-c100]