在 Groovy 中获取字符的 Unicode

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

在 Groovy 中有什么方法可以让我获得与任何字符等效的 Unicode?例如

假设一个方法 getUnicode(char c)。调用 getUnicode('÷') 应该返回 \u00f7.

groovy utf-16 utf
1个回答
0
投票

所以我要用这个打击你:

println( "\\u${'÷'.getBytes("UTF-16")[2..3].collect { String.format('%02x',it) }.join('')}" )

println("\\u${'÷'.getBytes("UTF-16BE").collect { String.format('%02x',it) }.join('')}")

诀窍是获取字节的 UTF-16 版本,否则它不会像你期望的那样工作。但是,

getBytes
返回 4 字节而不是 2 个字节,因为它在其前面包含 UTF BOM。因此,拼接索引 2 到 3 将仅隔离您需要的字符。使用
String.format
的十六进制格式,并使用 Groovy GString 将它们连接回 \u 字符上的字符串大头钉,让你做饭。

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