Golang implements several solutions for reverse ordering of strings


preface

This article mainly introduces the Golang implementation of string reverse order related content, Shared for your reference and learning, the following words are not enough, let’s start with a detailed introduction:

The string is inverted as follows:

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
  }

The general idea is:

str - Loop - > array - Cycle - > Invert — cycle — > str

You can switch to Chinese.

Question:

It looks tedious, and using a 3-layer cycle is definitely not efficient.

Solution 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

Using a 1-layer loop, invert and convert []byte to string directly using the built-in string function of go

General idea:

string — Directly use the array building method, pass in str, get array — > []byte —for cycle — > Invert - the built-in string function > string

Question:

Cannot convert byte type

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

Solution 2: Unable to convert Chinese characters:

conclusion

Reference:

string rune byte relationship