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.7k Golang : Grayscale Image
+13.6k Golang : Missing Bazaar command
+5.3k Golang : Handling image beyond OpenCV video capture boundary
+8.4k Golang : Format strings to SEO friendly URL example
+5.5k Golang : How to determine if request or crawl is from Google robots
+4.2k Golang : Qt update UI elements with core.QCoreApplication_ProcessEvents
+12.3k Golang : Get constant name from value
+11.4k Golang : zlib compress file example
+17.8k Golang : Fix cannot download, $GOPATH not set error
+23.7k Golang : Convert long hexadecimal with strconv.ParseUint example
+11.3k Golang : Covert map/slice/array to JSON or XML format
+15.5k Golang : Merge video(OpenCV) and audio(PortAudio) into a mp4 file