How to manipulate strings in GO to reverse them?

前端 未结 2 1365
孤街浪徒
孤街浪徒 2021-01-07 05:10

I\'m trying to invert a string in go but I\'m having trouble handling the characters. Unlike C, GO treats strings as vectors of bytes, rather than characters, which are call

2条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-07 05:59

    As you correctly identified, go strings are immutable, so you cannot assign to rune/character values at given indices.

    Instead of reversing the string in-place one must create a copy of the runes in the string and reverse those instead, and then return the resulting string.

    For example (Go Playground):

    func reverse(s string) string {
      rs := []rune(s)
      for i, j := 0, len(rs)-1; i < j; i, j = i+1, j-1 {
        rs[i], rs[j] = rs[j], rs[i]
      }
      return string(rs)
    }
    
    func main() {
      fmt.Println(reverse("Hello, World!"))
      // !dlroW ,olleH
      fmt.Println(reverse("Hello, 世界!"))
      // !界世 ,olleH
    }
    

    There are problems with this approach due to the intricacies of Unicode (e.g. combining diacritical marks) but this will get you started.

提交回复
热议问题