我们如何在Go中反转一个简单的字符串?
发布于 2016-09-04 00:02:32
以下两种方法的运行速度比最快的solution that preserve combining characters更快,但这并不是说我的基准测试设置中缺少了什么。
//input string s
bs := []byte(s)
var rs string
for len(bs) > 0 {
r, size := utf8.DecodeLastRune(bs)
rs += fmt.Sprintf("%c", r)
bs = bs[:len(bs)-size]
} // rs has reversed string受this启发的第二种方法
//input string s
bs := []byte(s)
cs := make([]byte, len(bs))
b1 := 0
for len(bs) > 0 {
r, size := utf8.DecodeLastRune(bs)
d := make([]byte, size)
_ = utf8.EncodeRune(d, r)
b1 += copy(cs[b1:], d)
bs = bs[:len(bs) - size]
} // cs has reversed byteshttps://stackoverflow.com/questions/1752414
复制相似问题