Search code examples
sortingalphanumeric

I want sorting on string which contains numbers and characters


I want sorting on string which contains number and character. First, it should sort number and then string. Input :

string[] alphanumeric = new string[] 
 {                 
 "0012", "0000","1200", "0002", "9700","AB10", "0IWZ", "XZYA", "0003", "ABCD"          
 };

Expected output:

0000
0002
0003
0012
0IWZ
1200
9700
AB10
ABCD
ZYYA

Solution

  • You should use Arrays.sort method like this:

    private void print(){
        String[] alphanumeric = new String[]
                {
                        "0012", "0000","1200", "0002", "9700","AB10", "0IWZ", "XZYA", "0003", "ABCD"
                };
    
        Arrays.sort(alphanumeric);
    
        System.out.println(Arrays.toString(alphanumeric));
        /* output: [0000, 0002, 0003, 0012, 0IWZ, 1200, 9700, AB10, ABCD, XZYA] */
    }