Golang符文在字符串或如何转换?

问题描述 投票:1回答:1

我有一个包含以下文字的字符串。

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

这不是文字。在字符串中,它存储为单独的字符,如['\','x','D','0','\','x','A','4',...]

如何将此字符串转换为普通字符?

string go decode rune
1个回答
1
投票

Go接受十六进制rune literals

因此,您可以将输入用作常规字符串:

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

Playground的例子。

如果从实际字符串["\" "x" "D" "0" ...]开始,则需要将单个4字节序列转换为字符。一种肮脏的方式是:

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的例子。

编辑回答编辑过的问题。

© www.soinside.com 2019 - 2024. All rights reserved.