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.1k Golang : How to get capacity of a slice or array?
+25.7k Golang : How to read integer value from standard input ?
+8.6k Golang : On lambda, anonymous, inline functions and function literals
+6k Golang : Extract XML attribute data with attr field tag example
+6k Golang : Dealing with backquote
+13.3k Golang : Count number of runes in string
+9.3k Golang : Web(Javascript) to server-side websocket example
+26.6k Golang : Convert file content into array of bytes
+5.4k PHP : Fix Call to undefined function curl_init() error
+9.2k Golang : Play .WAV file from command line
+7.3k Golang : Process json data with Jason package