使用Golang按名称对切片进行排序

huangapple go评论73阅读模式
英文:

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 (
	&quot;fmt&quot;
	&quot;sort&quot;
	&quot;strings&quot;
)

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] &lt; []rune(strings.ToLower(s[j]))[0]
}

func main() {
	data := []string{&quot;Ab&quot;, &quot;Aa&quot;, &quot;D&quot;, &quot;c&quot;}
	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]) &lt; strings.ToLower(s[j])
}

huangapple
  • 本文由 发表于 2021年12月20日 21:19:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/70422434.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定