在 Golang 中使用 sort.Strings() 进行不区分大小写的排序可以通过实现自定义比较函数来实现。下面是一个示例代码:
package main
import (
"fmt"
"sort"
"strings"
)
type caseInsensitive []string
func (s caseInsensitive) Len() int {
return len(s)
}
func (s caseInsensitive) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
func (s caseInsensitive) Less(i, j int) bool {
return strings.ToLower(s[i]) < strings.ToLower(s[j])
}
func main() {
fruits := []string{"Apple", "banana", "Cherry", "dates"}
fmt.Println("Before sorting:", fruits)
sort.Sort(caseInsensitive(fruits))
fmt.Println("After sorting:", fruits)
}
在上述示例中,我们定义了一个类型为 caseInsensitive 的切片,并且实现了该类型的三个方法:Len()、Swap() 和 Less()。其中,Len() 方法返回切片的长度,Swap() 方法用于交换两个元素的位置,Less() 方法用于比较两个元素的大小。
在 Less() 方法中,我们使用了 strings.ToLower() 函数将字符串转换为小写字母,从而实现了不区分大小写的比较。
最后,在 main() 函数中,我们先输出了排序前的切片,然后使用 sort.Sort() 函数和自定义的比较函数进行排序,最后再输出排序后的结果。