Reverse Slice of strings

Issue

I don’t understand what is wrong with the below implementation, I had a look at sort.StringSlice and it looks the same.

type RevStr []string

func(s RevStr) Len() int { return len(s) }
func(s RevStr) Less(i, j int) bool { return s[i] < s[j] }
func(s RevStr) Swap(i, j int) { s[i], s[j] = s[j], s[i] }

func Reverse(input string) string {
  rs := RevStr(strings.Split(input, " "))
  sort.Reverse(rs)
  return strings.Join(rs, " ")
}

Solution

sort.Reverse doesn’t sort the data, but rather returns a new sort.Interface that will sort the data in reverse order. So you don’t really need your own type:

func Reverse(input string) string {
    s := strings.Split(input, " ")
    sort.Sort(sort.Reverse(sort.StringSlice(s)))
    return strings.Join(s, " ")
}

Playground: http://play.golang.org/p/w49FDCEHo3.

EDIT: If you just need to reverse a slice of strings, just do:

func reverse(ss []string) {
    last := len(ss) - 1
    for i := 0; i < len(ss)/2; i++ {
        ss[i], ss[last-i] = ss[last-i], ss[i]
    }
}

Playground: http://play.golang.org/p/UptIRFV_SI

Answered By – Ainar-G

Answer Checked By – Marilyn (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.