简体   繁体   中英

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.

Another Linq solution (warning, converted from C#)

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

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()

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.

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

Output sequence is: green, blue, red.

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;
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM