How to reverse a string in Go?

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

How can we reverse a simple string in Go?

28条回答
  •  遥遥无期
    2020-12-04 07:34

    Russ Cox, on the golang-nuts mailing list, suggests

    package main 
    import "fmt"
    func main() { 
            input := "The quick brown 狐 jumped over the lazy 犬" 
            // Get Unicode code points. 
            n := 0
            rune := make([]rune, len(input))
            for _, r := range input { 
                    rune[n] = r
                    n++
            } 
            rune = rune[0:n]
            // Reverse 
            for i := 0; i < n/2; i++ { 
                    rune[i], rune[n-1-i] = rune[n-1-i], rune[i] 
            } 
            // Convert back to UTF-8. 
            output := string(rune)
            fmt.Println(output)
    }
    

提交回复
热议问题