How to reverse a string in Go?

前端 未结 28 1970
天涯浪人
天涯浪人 2020-12-04 06:45

How can we reverse a simple string in Go?

28条回答
  •  鱼传尺愫
    2020-12-04 07:35

    This code preserves sequences of combining characters intact, and should work with invalid UTF-8 input too.

    package stringutil
    import "code.google.com/p/go.text/unicode/norm"
    
    func Reverse(s string) string {
        bound := make([]int, 0, len(s) + 1)
    
        var iter norm.Iter
        iter.InitString(norm.NFD, s)
        bound = append(bound, 0)
        for !iter.Done() {
            iter.Next()
            bound = append(bound, iter.Pos())
        }
        bound = append(bound, len(s))
        out := make([]byte, 0, len(s))
        for i := len(bound) - 2; i >= 0; i-- {
            out = append(out, s[bound[i]:bound[i+1]]...)
        }
        return string(out)
    }
    

    It could be a little more efficient if the unicode/norm primitives allowed iterating through the boundaries of a string without allocating. See also https://code.google.com/p/go/issues/detail?id=9055 .

提交回复
热议问题