【问题标题】:sort a string slice: letters in alphabetical order *after* descending numbers对字符串切片进行排序:按字母顺序*在*降序后的字母
【发布时间】:2021-04-01 17:22:28
【问题描述】:

给定:

alphanumeric := ["aaa","bbb","ccc","111","222","333"]

排序后:

["333","222","111","aaa","bbb","ccc"]

尝试了内置排序包:

sort.Strings(alphanumeric)

它很接近,但数字部分将按升序排列

["111","222","333","aaa","bbb","ccc"]

还有:

sort.Slice(alphanumeric, func(i, j int) bool {
    return alphanumeric[i] > alphanumeric[j]
})

结果不想要:["ccc","bbb","aaa","333","222","111"]

对所有东西都很陌生,感谢您的任何提示

【问题讨论】:

  • 显示您尝试解决此问题的方法。
  • @BurakSerdar 抱歉更新了。
  • 不要在你的问题标题中加上“[SOLVED]”; SO对此有一个接受的答案的机制。如果您自己解决了问题,您可以发布自己问题的答案并接受它。

标签: string sorting go slice


【解决方案1】:

https://play.golang.org/p/hS4bo1q2tQl

sort.Slice(alphanumeric, func(i, j int) bool {
    // check if we have numbers, sort them accordingly 
    if z, err := strconv.Atoi(alphanumeric[i]); err == nil {
        if y, err := strconv.Atoi(alphanumeric[j]); err == nil {
        return y < z
    }
    // if we get only one number, alway say its greater than letter 
    return true
    }
    // compare letters normally 
    return alphanumeric[j] > alphanumeric[i]
})

【讨论】:

  • 非常感谢!顺便说一句,我发现如果数字以十进制表示(1.236/ 2.0 等)或代表某些版本号(1.0.0.2),这可能会失败。更新了一个小模组的帖子。
猜你喜欢
  • 1970-01-01
  • 2017-10-04
  • 2015-07-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-05
  • 2013-09-04
  • 1970-01-01
相关资源
最近更新 更多