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
+6.2k Fix ERROR 2003 (HY000): Can't connect to MySQL server on 'IP address' (111)
+6k Unix/Linux : How to open tar.gz file ?
+8.9k Golang : Gorilla web tool kit schema example
+19.5k Golang : Get host name or domain name from IP address
+7.9k Golang : Load DSA public key from file example
+9.2k Golang : io.Reader causing panic: runtime error: invalid memory address or nil pointer dereference
+35.3k Golang : Upload and download file to/from AWS S3
+6.7k Golang : Convert an executable file into []byte example
+14.9k Golang : Normalize unicode strings for comparison purpose
+15.2k Golang : Search folders for file recursively with wildcard support
+16.2k Golang : ROT47 (Caesar cipher by 47 characters) example
+28.2k Golang : Move file to another directory