我希望字符串按字母顺序排序,并控制“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/