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.1k Golang : How to stop user from directly running an executable file?
+10k Golang : Generate random integer or float number
+13k Golang : Get constant name from value
+28.8k Golang : How to create new XML file ?
+19.9k Nginx + FastCGI + Go Setup.
+11.9k Golang : How to display image file or expose CSS, JS files from localhost?
+20.2k Golang : Saving private and public key to files
+16.3k Golang : Get the IPv4 and IPv6 addresses for a specific network interface
+4.1k Golang : Valued expressions and functions example
+14.2k Golang : Execute function at intervals or after some delay
+7.5k Javascript : Put image into Chrome browser's console
+6.7k Golang : Fixing Gorilla mux http.FileServer() 404 problem