【问题标题】:Numeric string sorting with letters and numbers in Groovy在 Groovy 中使用字母和数字对数字字符串进行排序
【发布时间】:2012-08-29 01:53:23
【问题描述】:

简单的问题,不知道有没有简单的答案。 有没有办法对包含字母和数字的字符串列表进行排序,但也要考虑数字?

例如,我的列表包含:

(1) ["Group 1", "Group2", "Group3", "Group10", "Group20", "Group30"]

(字符串不一定有“组”这个词,也可以有其他词)

如果我对其进行排序,它会显示:

(2)
Group 1
Group 10
Group 2
Group 20
Group 3
Group 30

有没有办法像 (1) 一样对其进行排序?

谢谢

【问题讨论】:

    标签: string sorting groovy numeric


    【解决方案1】:

    这应该可以解决问题:

    def myList= ["Group 1", "Group2", "Group3", "2", "Group20", "Group30", "1", "Grape 1"]
    print (myList.sort { a, b -> a.compareToIgnoreCase b })
    

    【讨论】:

      【解决方案2】:

      您可以将字符串拆分为两个子字符串,然后分别对它们进行排序。

      【讨论】:

        【解决方案3】:

        试试这个:

        def test=["Group 1", "Group2", "Group3", "2", "Group20", "Group30", "1", "Grape 1", "Grape 12", "Grape 2", "Grape 22"]
        
        test.sort{ a,b ->
            def n1 = (a =~ /\d+/)[-1] as Integer
            def n2 = (b =~ /\d+/)[-1] as Integer
        
            def s1 = a.replaceAll(/\d+$/, '').trim()
            def s2 = b.replaceAll(/\d+$/, '').trim()
        
            if (s1 == s2){
                return n1 <=> n2
            }
            else{
                return s1 <=> s2
            }
        }
        
        println test
        

        如果您想首先比较数字,您必须将内部 if 更改为:

        if (n1 == n2){
            return s1 <=> s2
        }
        else{
            return n1 <=> n2
        }
        

        这取它在字符串中找到的最后一个数字,所以你可以写你想要的,但“索引”应该是最后一个数字

        【讨论】:

        • 非常好的尝试兄弟,但用这个测试:def test= ["Group 1", "Group2", "Group3", "2", "Group20", "Group30", "1", "Grape 1", "Grape 12", "Grape 2", "Grape 22"]
        • 结果应该是什么?它应该首先检查数字而不是字符串?还是首先是字符串而不是数字?
        • 显示来自测试的 println [Group 1, 1, Grape 1, Group2, 2, Grape 2, Group3, Grape 12, Group20, Grape 22, Group30] 你在这里看到什么顺序?
        • 真的很酷! +10。 s1 &lt;=&gt; s2 : n1 &lt;=&gt; n2 你可以更简洁
        • 也许还有一个if 来检查integer 是否存在。但这太过分了。很好的答案兄弟。
        猜你喜欢
        • 2013-12-21
        • 1970-01-01
        • 2013-06-05
        • 1970-01-01
        • 2020-11-13
        • 2016-10-28
        • 2021-09-19
        • 2021-09-17
        相关资源
        最近更新 更多