How to reverse a string in Go?

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

How can we reverse a simple string in Go?

28条回答
  •  情话喂你
    2020-12-04 07:27

    The following two methods run faster than the fastest solution that preserve combining characters, though that's not to say I'm missing something in my benchmark setup.

    //input string s
    bs := []byte(s)
    var rs string
    for len(bs) > 0 {
        r, size := utf8.DecodeLastRune(bs)
        rs += fmt.Sprintf("%c", r)
        bs = bs[:len(bs)-size]
    } // rs has reversed string
    

    Second method inspired by this

    //input string s
    bs := []byte(s)
    cs := make([]byte, len(bs))
    b1 := 0
    for len(bs) > 0 {
        r, size := utf8.DecodeLastRune(bs)
        d := make([]byte, size)
        _ = utf8.EncodeRune(d, r)
        b1 += copy(cs[b1:], d)
        bs = bs[:len(bs) - size]
    } // cs has reversed bytes
    

提交回复
热议问题