How to reverse a string in Go?

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

How can we reverse a simple string in Go?

28条回答
  •  执笔经年
    2020-12-04 07:29

    Here is yet another solution:

    func ReverseStr(s string) string {
        chars := []rune(s)
        rev := make([]rune, 0, len(chars))
        for i := len(chars) - 1; i >= 0; i-- {
            rev = append(rev, chars[i])
        }
        return string(rev)
    }
    

    However, yazu's solution above is more elegant since he reverses the []rune slice in place.

提交回复
热议问题