0

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)
}
Marius
  • 537
  • 1
  • 6
  • 23
  • 4
    Then compare the strings, not just the first runes: `strings.ToLower(s[i]) < strings.ToLower(s[j])` – icza Dec 20 '21 at 13:30
  • The Go Playground example from the answer where the code is from ( https://stackoverflow.com/a/51997951 ) uses only the first index because the OP of that question only had strings with only a single character. – Zyl Dec 20 '21 at 13:32
  • For better performance consider a [case-insensitive compare](https://stackoverflow.com/questions/30196780/case-insensitive-string-comparison-in-go) instead of `strings.ToLower` during each comparison. – rustyx Dec 20 '21 at 13:34

1 Answers1

2

[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])
}
Miguel Cabrera
  • 191
  • 1
  • 6