繁体   English   中英

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

[英]How to sort array of strings by their lengths

我有一个字符串数组,例如“blue”、“green”、“red”,我希望对它们进行排序,以便最长的字符串排在最前面,最短的排在最后。

目前我正在创建另一个数组,数组中每个字符串的长度都在相同的索引位置,并使用这个数组作为键数组进行排序,如下所示,但我认为这也许可以优化成一行?

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)

编辑:刚刚意识到我在示例代码中将颜色定义为一个列表,它在我的实际代码中是一个数组。

另一种Linq解决方案(警告,由C#转换而来)

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

在我看来,这是最短的方式。 使用 linq。

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

编辑

如果您想要相反的顺序,只需摆脱额外的方法调用并以相反的顺序进行排序

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

干杯。

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

Output 顺序是:绿、蓝、红。

最简单的方法是将每个字符串与列表中的所有其他字符串进行比较:

在 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