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
+12.6k Golang : Convert int(year) to time.Time type
+25.5k Golang : Convert IP address string to long ( unsigned 32-bit integer )
+14k Android Studio : Use image as AlertDialog title with custom layout example
+7.9k Golang : Get final or effective URL with Request.URL example
+8.2k Golang : Ackermann function example
+16.2k CodeIgniter/PHP : Create directory if does not exist example
+4.4k Adding Skype actions such as call and chat into web page examples
+10.6k PHP : Convert(cast) bigInt to string
+4.9k Golang : Convert lines of string into list for delete and insert operation
+14.2k Golang : Find network of an IP address
+11.4k Golang : Calculations using complex numbers example
+10.7k Golang : Replace a parameter's value inside a configuration file example