Golang : Reverse a string with unicode
Problem :
You got a string of :
世界你好! is the equivalent of Hello World! in Chinese
and you need to reverse this string.
Solution :
Use unicode/utf8
package to handle the runes and reverse the string with this program below :
package main
import (
"fmt"
"unicode/utf8"
)
var forward string = "世界你好! is the equivalent of Hello World! in Chinese"
func Reverse(s string) string {
totalLength := len(s)
buffer := make([]byte, totalLength)
for i := 0; i < totalLength; {
r, size := utf8.DecodeRuneInString(s[i:])
i += size
utf8.EncodeRune(buffer[totalLength-i:], r)
}
return string(buffer)
}
func main() {
fmt.Println("Original : ", forward)
backward := Reverse(forward)
fmt.Println("Reversed : ", backward)
}
Output :
Original : 世界你好! is the equivalent of Hello World! in Chinese
Reversed : esenihC ni !dlroW olleH fo tnelaviuqe eht si !好你界世
Hope this reverse function can be useful to you.
See also : Golang : Sort and reverse sort a slice of strings
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+10.8k Golang : Get currencies exchange rates example
+14k Golang : unknown escape sequence error
+5.3k Golang : The Tao of importing package
+8.1k Golang : Trim everything onward after a word
+5k Unix/Linux : secure copying between servers with SCP command examples
+7.6k Golang : Check to see if *File is a file or directory
+5.5k Golang : Qt update UI elements with core.QCoreApplication_ProcessEvents
+18k Golang : How to make a file read only and set it to writable again?
+16.5k Golang : Loop each day of the current month example
+17.8k Convert JSON to CSV in Golang
+5.9k Golang : Fix opencv.LoadHaarClassifierCascade The node does not represent a user object error
+17.2k Golang : Get input from keyboard