How to reverse a string in Go?

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

How can we reverse a simple string in Go?

28条回答
  •  星月不相逢
    2020-12-04 07:26

    This works on unicode strings by considering 2 things:

    • range works on string by enumerating unicode characters
    • string can be constructed from int slices where each element is a unicode character.

    So here it goes:

    func reverse(s string) string {
        o := make([]int, utf8.RuneCountInString(s));
        i := len(o);
        for _, c := range s {
            i--;
            o[i] = c;
        }
        return string(o);
    }
    

提交回复
热议问题