sorting - 在 Golang 中,如何在不完全忽略大小写的情况下按字母顺序对字符串列表进行排序?

标签 sorting go alphabetical-sort

我希望字符串按字母顺序排序,并控制“A”是否出现在“a”之前。

在 Less() 函数中使用 strings.ToLower() 无法实现这一点。有时“A”出现在“a”之前,有时出现在“a”之后。

最佳答案

不是使用 strings.ToLower 比较整个字符串,而是比较单个 rune 。

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

type ByCase []string

func (s ByCase) Len() int      { return len(s) }
func (s ByCase) Swap(i, j int) { s[i], s[j] = s[j], s[i] }

func (s ByCase) Less(i, j int) bool {
    iRunes := []rune(s[i])
    jRunes := []rune(s[j])

    max := len(iRunes)
    if max > len(jRunes) {
        max = len(jRunes)
    }

    for idx := 0; idx < max; idx++ {
        ir := iRunes[idx]
        jr := jRunes[idx]

        lir := unicode.ToLower(ir)
        ljr := unicode.ToLower(jr)

        if lir != ljr {
            return lir < ljr
        }

        // the lowercase runes are the same, so compare the original
        if ir != jr {
            return ir < jr
        }
    }

    // If the strings are the same up to the length of the shortest string, 
    // the shorter string comes first
    return len(iRunes) < len(jRunes)
}

关于sorting - 在 Golang 中,如何在不完全忽略大小写的情况下按字母顺序对字符串列表进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35076109/

相关文章:

swift - 如何对 NSUserDefault 中的 NSMutableDictionary 存储数组进行排序?

go - 从字符串列表初始化结构

python - 按字母顺序对字符串列表进行排序

r - 按字母顺序排序时,字母 "y"位于 "i"之后

javascript - 根据另一个属性的升序对已排序的对象数组进行排序

python - 合并两个排序列表时,为什么我会得到两个不同的输出 (Python)

Golang 类型在指向一种类型 slice 的指针 slice 与另一种类型 slice 之间的类型转换

pointers - Go 中独特的函数集合

PHP fatal error : Class 'Collator' not found despite PHP 5. 3.24

angular - TypeError : Cannot read property 'sort' of undefined at SortPipe. 转换,为什么?