Golang runes in string or how to convert?

961 Views Asked by At

I have a string which contains following text.

\xD0\xA4\xD0\xB5\xD0\xB4\xD0\xBE\xD1\x80\xD0\xBE\xD0\xB2

It is not a literal. In string it's stored as separate characters like this ['\','x','D','0','\','x','A','4',...]

How to convert this string to normal characters?

1

There are 1 best solutions below

9
On BEST ANSWER

Go accepts hexadecimal rune literals.

So you can use your input as a regular string:

fmt.Println("\xD0\xA4\xD0\xB5\xD0\xB4\xD0\xBE\xD1\x80\xD0\xBE\xD0\xB2")
Федоров

Playground example.

If you start with the actual string ["\" "x" "D" "0" ...], you'll need to convert the individual 4-byte sequences to characters. One dirty way is:

s := `\xD0\xA4\xD0\xB5\xD0\xB4\xD0\xBE\xD1\x80\xD0\xBE\xD0\xB2`
s2, _ := hex.DecodeString(strings.Replace(s, "\\x", "", -1))
fmt.Printf("%s", s2)

Playground example.

Edited to answer edited question.