Golang string Inversion

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

String inversion

Hello World--Dlrow Olleh

  • Solution 1:

          length := len(str)      array := make([]string ,  length)      for i , v := range str{          array[i] = string(v)      }      for i := 0 ; i < length/2 ; i++ {          array[i], array[length -i - 1] = array[length - i -1 ],  array[i]      }      str = ""      for _ , v := range array {          str += v      }      大致想法是:            str -循环-> array -循环-> 倒置 --循环--> str      可以转换中文.      问题:          看上去比较繁琐, 而且使用3层循环, 效率肯定不高,
  • Solutions 2

      bytes := []rune(str)  for from , to := 0 , len(bytes) -1 ; from < to ; from , to = from + 1, to -1{      bytes[from] , bytes[to] = bytes[to] , bytes[from]  }  str = string(bytes)  return str 使用一层循环, 倒置之后 直接使用 go 内置的 string 函数将 []byte 转换为string  大致思路:   string --直接使用构建数组的方法, 将str 传入进去, 得到 array --> []byte ---for 循环---> 倒置 ---内置的 string 函数--> string 问题:      不能转换 byte 类型
  • Solution 3:

      bytes := []rune(str)  for from , to := 0 , len(bytes) -1 ; from < to ; from , to = from + 1, to -1{      bytes[from] , bytes[to] = bytes[to] , bytes[from]  }  str = string(bytes)  return str      解决方案2不能转换中文字符的问题:
  • Reference:

The relationship of String rune byte

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.