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
+11.3k Golang : How to display image file or expose CSS, JS files from localhost?
+12.6k Golang : How to check if a file is hidden?
+11k Golang : Encrypt and decrypt data with x509 crypto
+11.1k Golang : Display list of countries and ISO codes
+3.5k Java : Generate multiplication table example
+10.7k Golang : Clean formatting/indenting or pretty print JSON result
+6k Golang : Squaring elements in array
+11.6k Golang : Convert int(year) to time.Time type
+3.9k Javascript : How to get width and height of a div?
+28.9k Golang : Generate random string
+4.7k Linux/Unix/PHP : Restart PHP-FPM
+25.8k Golang : Convert CSV data to JSON format and save to file