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
+50.1k Golang : Check if item is in slice/array
+4.3k Golang : The Tao of importing package
+6k Linux : How to fix Brother HL-1110 printing blank page problem
+4.5k Golang : If else example and common mistake
+6.4k Golang : Get YouTube playlist
+12.8k Golang : Simple word wrap or line breaking example
+15.4k Golang : read gzipped http response
+3.3k Golang : Converting individual Jawi alphabet to Rumi(Romanized) alphabet example
+14.3k Golang : invalid character ',' looking for beginning of value
+9.6k Golang : Get local time and equivalent time in different time zone
+10.4k Golang : Concurrency and goroutine example
+4.1k Linux/Unix/MacOSX : Find out which application is listening to port 80 or use which IP version