Preface
This article mainly introduces the relevant content about Golang's implementation of reverse string ordering. We will share it for your reference and learning. I won't say much below. Let's take a look at the detailed introduction together:
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 -loop-> inverted --loop--> str
Can convert Chinese.
question:
It looks quite cumbersome, and it uses 3-layer loops, so the efficiency is definitely not high.
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
Use a layer of loop, and then invert it directly use go's built-in string function to convert []byte to string
General idea:
string -- directly use the method of building an array, pass str in, and get array --> []byte ---for loop ---> inversion --- 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: The problem of not converting Chinese characters:
Summarize
The above is the entire content of this article. I hope that the content of this article has certain reference value for everyone's study or work. If you have any questions, you can leave a message to communicate. Thank you for your support.
refer to:
string rune byte relationship