Scala在两个字符集之间转换字符串

时间:2016-09-22 15:39:58

标签: scala utf-8 character-encoding

我有一个错误的UTF-8字符串,应该写成“MichèleHuà”,但输出为“MichèleHuÔ

根据此表,它是Windows-1252和UTF-8之间的问题 http://www.i18nqa.com/debug/utf8-debug.html

如何进行转换?

scala> scala.io.Source.fromBytes("Michèle HuÃ".getBytes(), "ISO-8859-1").mkString
res25: String = Michèle HuÃ

scala> scala.io.Source.fromBytes("Michèle HuÃ".getBytes(), "UTF-8").mkString
res26: String = Michèle HuÃ

scala> scala.io.Source.fromBytes("Michèle HuÃ".getBytes(), "Windows-1252").mkString
res27: String = Michèle HuÃ

谢谢

1 个答案:

答案 0 :(得分:4)

由于一个字符打印空白的不幸问题,您实际上并没有完整的字符串。 “MichèleHuà”编码为UTF-8但读作Windows-1252实际上是“MichèleHu”,其中最后一个字符是0xA0(但通常粘贴为0x20,一个空格)。

如果您可以加入该字符,则可以成功转换。

scala> fixed = new String("Michèle HuÃ\u00A0".getBytes("Windows-1252"), "UTF-8")
fixed: String = Michèle Huà