How to reverse a string in Go?

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

How can we reverse a simple string in Go?

28条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-04 07:18

    try below code:

    package main
    
    import "fmt"
    
    func reverse(s string) string {
        chars := []rune(s)
        for i, j := 0, len(chars)-1; i < j; i, j = i+1, j-1 {
            chars[i], chars[j] = chars[j], chars[i]
        }
        return string(chars)
    }
    
    func main() {
        fmt.Printf("%v\n", reverse("abcdefg"))
    }
    

    for more info check http://golangcookbook.com/chapters/strings/reverse/
    and http://www.dotnetperls.com/reverse-string-go

提交回复
热议问题