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
+13.5k Golang : Rename directory
+8k Golang : Serving HTTP and Websocket from different ports in a program example
+16.5k Golang : Simple client server example
+14.8k Golang : Get sub string example
+12.8k How to automatically restart your crashed Golang server
+3.3k Golang : Converting individual Jawi alphabet to Rumi(Romanized) alphabet example
+11.7k Android Studio : Password input and reveal password example
+9.8k Golang : Removes punctuation or defined delimiter from the user's input
+5.9k Golang : Levenshtein distance example
+19.3k PHP : Convert(cast) int to double/float
+10k Golang : Fix fmt.Scanf() on Windows will scan input twice problem
+7.5k Golang : How to capture return values from goroutines?