-
慕桂英3389331
不是使用 比较整个字符串strings.ToLower,而是比较单个符文。https://play.golang.org/p/RUMlmrb7C3gtype ByCase []stringfunc (s ByCase) Len() int { return len(s) }func (s ByCase) Swap(i, j int) { s[i], s[j] = s[j], s[i] }func (s ByCase) Less(i, j int) bool { iRunes := []rune(s[i]) jRunes := []rune(s[j]) max := len(iRunes) if max > len(jRunes) { max = len(jRunes) } for idx := 0; idx < max; idx++ { ir := iRunes[idx] jr := jRunes[idx] lir := unicode.ToLower(ir) ljr := unicode.ToLower(jr) if lir != ljr { return lir < ljr } // the lowercase runes are the same, so compare the original if ir != jr { return ir < jr } } // If the strings are the same up to the length of the shortest string, // the shorter string comes first return len(iRunes) < len(jRunes)}
-
SMILET
这可能是一个解决方案:package mainimport ( "strings" "sort" "fmt")var listOfStrings []string = []string{ "mars bar", "milk-duds", "Mars bar", "milk", "milky-way", "Milk", "Milky-way", "mars",}type Alphabetic []stringfunc (list Alphabetic) Len() int { return len(list) }func (list Alphabetic) Swap(i, j int) { list[i], list[j] = list[j], list[i] }func (list Alphabetic) Less(i, j int) bool { var si string = list[i] var sj string = list[j] var si_lower = strings.ToLower(si) var sj_lower = strings.ToLower(sj) if si_lower == sj_lower { return si < sj } return si_lower < sj_lower}func main() { fmt.Println("UNSORTED") printStrings(listOfStrings) sort.Sort(Alphabetic(listOfStrings)) fmt.Println() fmt.Println("SORTED ALPHABETICALLY") printStrings(listOfStrings)}func printStrings(slice []string) { for i := 0; i < len(slice); i++ { fmt.Println(slice[i]) }}这是输出:UNSORTEDmars barmilk-dudsMars barmilkmilky-wayMilkMilky-waymarsSORTED ALPHABETICALLYmarsMars barmars barMilkmilkmilk-dudsMilky-waymilky-way
-
慕哥6287543
这是一个 Unicode 友好的方法,它利用strings.Map:package mainimport ( "fmt" "sort" "strings" "unicode")type slice struct { sort.StringSlice }func (s slice) Less(d, e int) bool { t := strings.Map(unicode.ToUpper, s.StringSlice[d]) u := strings.Map(unicode.ToUpper, s.StringSlice[e]) return t < u}func main() { a := slice{ sort.StringSlice{"a", "b", "A", "B"}, } sort.Sort(a) fmt.Println(a.StringSlice) // [a A b B]}https://golang.org/pkg/strings#Map