英文:
Golang sorting slices by name
问题
我有一个包含结构体的切片,结构体有一个名为name
的属性,类型为string
,我需要按照结构体的名称对切片进行字母顺序排序,而且不区分大小写。
下面是一个示例代码,它们对一个字符串切片进行排序,对我来说也可以工作,但问题是这段代码只考虑字符串的第一个字母。所以如果你尝试打印代码,"Ab"会被放在"Aa"之前,而我希望代码考虑字符串的每个字母,而不仅仅是第一个字母。
有人遇到过这个问题吗?也许你有解决方案?谢谢。
package main
import (
"fmt"
"sort"
"strings"
)
type byLength []string
func (s byLength) Len() int {
return len(s)
}
func (s byLength) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
func (s byLength) Less(i, j int) bool {
return strings.ToLower(s[i]) < strings.ToLower(s[j])
}
func main() {
data := []string{"Ab", "Aa", "D", "c"}
sort.Sort(byLength(data))
fmt.Println(data)
}
英文:
I have an slice of structs which have a property name
of type string
and I need to sort the slice alphabetically by name of the struct with it not being case sensitive.
Bellow is the code every example gives where they sort a slice of string, witch would work for me, but the problem is that this code only takes into account the first letter of the string. So if you would try to print the code out Ab would be put before Aa and I would like the code to take into account every letter of the string and not only the first one.
Has anyone encountered this and maybe you have a solution? Thank you.
package main
import (
"fmt"
"sort"
"strings"
)
type byLength []string
func (s byLength) Len() int {
return len(s)
}
func (s byLength) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
func (s byLength) Less(i, j int) bool {
return []rune(strings.ToLower(s[i]))[0] < []rune(strings.ToLower(s[j]))[0]
}
func main() {
data := []string{"Ab", "Aa", "D", "c"}
sort.Sort(byLength(data))
fmt.Println(data)
}
答案1
得分: 2
[更新]: 如评论中的@colm.anseo所说,我修复了对不区分大小写排序的函数。
错误出现在Less
方法的实现上。你只是评估了字符串的第一个字符(将其转换为rune
的切片,然后取第一个字母)。将该方法的实现更改为以下内容:
func (s byLength) Less(i, j int) bool {
return strings.ToLower(s[i]) < strings.ToLower(s[j])
}
英文:
[UPDATE]: As @colm.anseo says in the comments, I patch the function for a case-insensitive sorting.
The error is in the implementation of the Less
method. You're just evaluating the first character of the string (casting as a slice of rune
and then taking the first letter). Change the implementation of the method to this:
func (s byLength) Less(i, j int) bool {
return strings.ToLower(s[i]) < strings.ToLower(s[j])
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论