小编Jos*_*ark的帖子

Why does sorted "tan" != "ant"?

I'm trying to sort the characters in a string by sorting a slice of the bytes in the string (using sort.Slice). The code I'm using gets the right results sometimes but other times produces results I can't make sense of.

package main

import (
    "fmt"
    "sort"
)

func main() {
    for _, s := range []string{"nat", "tan", "ant"} {
        b := []byte(s)
        sort.Slice(b, func(i int, j int) bool { return s[i] < s[j] })
        fmt.Println(s, string(b))
    }
}
Run Code Online (Sandbox Code Playgroud)

https://play.golang.org/p/bC9QWq7aF3G

I …

sorting string go

1
推荐指数
1
解决办法
90
查看次数

标签 统计

go ×1

sorting ×1

string ×1