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
+7.5k Golang : Generate Datamatrix barcode
+18.3k Golang : Example for DSA(Digital Signature Algorithm) package functions
+5.9k CloudFlare : Another way to get visitor's real IP address
+16.2k Golang : Qt image viewer example
+3.2k Detect if Google Analytics and Developer Media are loaded properly or not
+6.2k Golang : Check if one string(rune) is permutation of another string(rune)
+10.4k Golang : How to flush a channel before the end of program?
+38.3k Golang : UDP client server read write example
+4k MariaDB/MySQL : Form select statement or search query with Chinese characters
+37.9k Golang : How to iterate over a []string(array)
+7.2k Golang : Oanda bot with Telegram and RSI example