我在按字符排序字符串时遇到问题(要检查两个字符串是否是字谜,我想对它们都进行排序,并检查是否相等)。
我可以像这样得到字符串 s
的 []rune
表示:
runes := make([]rune, len(s))
copy(runes, []rune(s))
我可以像这样对整数进行排序
someInts := []int{5, 2, 6, 3, 1, 4} // unsorted
sort.Ints(someInts)
但 rune
只是 int32
的别名,所以我应该可以调用
sort.Ints(runes)
但是,我得到了错误:
cannot use runes (type []rune) as type []int in function argument
那么...如何对 int32、int64 或 int* 的 slice 进行排序?
编辑:我确实整理了我的 rune ,但是男孩,这很难看。
type RuneSlice []rune
func (p RuneSlice) Len() int { return len(p) }
func (p RuneSlice) Less(i, j int) bool { return p[i] < p[j] }
func (p RuneSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
func sorted(s string) string {
runes := []rune(s)
sort.Sort(RuneSlice(runes))
return string(runes)
}
所以基本上,如果你有一个 slice ,你必须将它包装在一个实现 sort.Interface
的类型中。所有这些实现都将具有完全相同的方法体(如 sort.IntSlice
和 sort.Float64Slice
)。如果这真的是多么丑陋,那么他们为什么不在 sort
包中提供这些 WhatSlice 包装器呢?缺乏泛型现在开始受到非常严重的伤害。必须有更好的方法来分类事物。
最佳答案
使用 sort.Sort(data Interface)
并实现sort.Interface
,请参阅包文档中的示例。
您不能将 int32
的 rune
用作 int
。查看comment int
.
int is a signed integer type that is at least 32 bits in size. It is a distinct type, however, and not an alias for, say, int32.
关于string - 去整理一片 rune ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18171136/