简体   繁体   English

如何按长度对字符串数组进行排序

[英]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.我有一个字符串数组,例如“blue”、“green”、“red”,我希望对它们进行排序,以便最长的字符串排在最前面,最短的排在最后。

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#)另一种Linq解决方案(警告,由C#转换而来)

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

To my opinion this is the shortes way.在我看来,这是最短的方式。 Use linq.使用 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.干杯。

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

Output sequence is: green, blue, red. Output 顺序是:绿、蓝、红。

The best simple way to do it, is to compare every string with all other strings in your list:最简单的方法是将每个字符串与列表中的所有其他字符串进行比较:

in Java:在 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;
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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