Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I need to sort an array of strings like the following, by a substring of characters:

[0] = "gtrd3455";
[1] = "wsft885";
[2] = "ltzy96545";
[3] = "scry5558";
[4] = "lopa475";

I need to sort by the following "3455, 885, 96545, 5558, 475" I need to substring off the first 4 characters of the array, sort it and display back in an array like the output below.

The output should be an array like:

[0] = "ltzy96545";
[1] = "scry5558";
[2] = "gtrd3455";
[3] = "wsft885";
[4] = "lopa475";

Example of how I can do this in Java?

share|improve this question
2  
What have you tried so far? –  Rohit Jain Oct 24 '12 at 19:19

1 Answer 1

up vote 3 down vote accepted

You can use a Comparator, and use Array#sort method with it, to sort it according to your need: -

String[] yourArray = new String[3];
yourArray[0] = "gtrd3455";
yourArray[1] = "ltzy96545";
yourArray[2] = "lopa475";

Arrays.sort(yourArray, new Comparator<String>() {
    public int compare(String str1, String str2) {
        String substr1 = str1.substring(4);
        String substr2 = str2.substring(4);

        return Integer.valueOf(substr2).compareTo(Integer.valueOf(substr1));
    }
});

System.out.println(Arrays.toString(yourArray));

OUTPUT: -

[ltzy96545, gtrd3455, lopa475]
share|improve this answer
    
@NullUserException. Also You missed a valid error though. I used compareTo on Integer.parseInt. which returns primitive int. ;) –  Rohit Jain Oct 24 '12 at 19:42
    
@NullUserException. Aww!! Man, you got me. Slipped from my mind.. –  Rohit Jain Oct 24 '12 at 19:44
    
@NullUserException. Edited :) –  Rohit Jain Oct 24 '12 at 19:45
    
How can I read in lines of a text file and add each line to the string array? Then do the sorting based on that dynamic array. –  Jsn0605 Oct 26 '12 at 12:46
    
@Jsn0605 For that you need to first fill your Array from the text file. And then the remaining process is same. –  Rohit Jain Oct 26 '12 at 12:47

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.