How to reverse a string in Go?

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

How can we reverse a simple string in Go?

28条回答
  •  無奈伤痛
    2020-12-04 07:32

    I noticed this question when Simon posted his solution which, since strings are immutable, is very inefficient. The other proposed solutions are also flawed; they don't work or they are inefficient.

    Here's an efficient solution that works, except when the string is not valid UTF-8 or the string contains combining characters.

    package main
    
    import "fmt"
    
    func Reverse(s string) string {
        n := len(s)
        runes := make([]rune, n)
        for _, rune := range s {
            n--
            runes[n] = rune
        }
        return string(runes[n:])
    }
    
    func main() {
        fmt.Println(Reverse(Reverse("Hello, 世界")))
        fmt.Println(Reverse(Reverse("The quick brown 狐 jumped over the lazy 犬")))
    }
    

提交回复
热议问题