Marcus Lars
Marcus Lars

Reputation: 51

How to sort array of strings by their lengths

I have an array of strings such as "blue", "green", "red" and I wish to sort them so the longest string comes first and the shortest last.

Currently I am creating another array with the lengths of each string in the array in the same index positions and using this array as the key array to sort by as can be seen below, but I think this could be optimised into one line perhaps?

Dim colours() As string = {"blue", "green", "red"}
Dim colourslength() As Integer
For i As Integer = 0 To colours.Length - 1
 colourslength(i) = colours(i).Length
Next
Array.Sort(colourslength, colours)
Array.Reverse(colours)

Edit: just realised I defined colours as a list in the example code, it's an array in my actual code.

Upvotes: 3

Views: 8225

Answers (4)

Ahmed Laatabi
Ahmed Laatabi

Reputation: 927

The best simple way to do it, is to compare every string with all other strings in your list:

in Java:

for(int i=0; i<list.length-1; i++){
    for(int j=i+1; j<list.length; j++){
        if(list[i].length() < list[j].length()){
            tmp = list[i];
            list[i] = list[j];
            list[j] = tmp;
        }
    }
}

Upvotes: 2

Steve Wellens
Steve Wellens

Reputation: 20620

Another Linq solution (warning, converted from C#)

Dim Sorted = From p In colours Order By p.Length Descending Select p

Upvotes: 5

Meta-Knight
Meta-Knight

Reputation: 17845

Dim colours = {"blue", "green", "red"}
Dim coloursSortedByLength = colours.OrderByDescending(Function(c) c.Length)

Output sequence is: green, blue, red.

Upvotes: 3

Oybek
Oybek

Reputation: 7243

To my opinion this is the shortes way. Use linq.

Dim strs = New String() {"", "333", "22", "4444", "55555", "1"}
Dim sorted = strs.OrderBy(Function(x) x.Length).ThenBy(Function(x) x).ToArray()

Edit

If you want a reverse order just get rid of extra method call an do the sortin in a reverse order

Dim strs = New String() {"", "333", "22", "4444", "55555", "1"}
Dim sorted = strs.OrderByDescending(Function(x) x.Length).ThenByDescending(Function(x) x).ToArray

Cheers.

Upvotes: 3

Related Questions