Go: Reverse a UTF-8 encoded string

This function returns a string with the UTF-8 encoded characters of s in reverse order. Invalid UTF-8 sequences, if any, will be reversed byte by byte.

func ReverseUTF8(s string) string {
        res := make([]byte, len(s))
        prevPos, resPos := 0, len(s)
        for pos := range s {
                resPos -= pos - prevPos
                copy(res[resPos:], s[prevPos:pos])
                prevPos = pos
        }
        copy(res[0:], s[prevPos:])
        return string(res)
}

Example usage:

for _, s := range []string{
        "Ångström",
        "Hello, 世界",
        "\xff\xfe\xfd", // invalid UTF-8
} {
        fmt.Printf("%q\n", ReverseUTF8(s))
}
"mörtsgnÅ"
"界世 ,olleH"
"\xfd\xfe\xff"

Comments

Be the first to comment!