【发布时间】:2015-09-27 14:46:30
【问题描述】:
如何在 android 中将字符串更改为 UTF-8 格式?例如,当我从服务器获取文本字符串时,我想将文本格式更改为 UTF-8。我该怎么做?
String getText = text; // this text variable has a value from the server and now I want change it to UTF-8 format.
【问题讨论】:
如何在 android 中将字符串更改为 UTF-8 格式?例如,当我从服务器获取文本字符串时,我想将文本格式更改为 UTF-8。我该怎么做?
String getText = text; // this text variable has a value from the server and now I want change it to UTF-8 format.
【问题讨论】:
String 对象在内部保存 UTF-16 数据。如果您想要将String 编码为UTF-8 进行导出,则需要将其转换为UTF-8 编码的byte[] 数组,例如使用String.getBytes(Charset charset) 或String.getBytes(String charsetName) 方法,例如:
byte[] byteArray = text.getBytes(StandardCharsets.UTF_8);
byte[] byteArray = text.getBytes("UTF-8");
【讨论】:
您好,您可以使用带有 charset 参数的 String 构造函数:
try
{
final String s = new String("AnyStringThatYouwant to convert", "UTF-8");
}
catch (UnsupportedEncodingException e)
{
Log.e("utf8", "conversion", e);
}
【讨论】:
String 构造函数。所有接受字符集作为输入的构造函数都期望byte[] 数组作为输入。 String 仅保存 UTF-16 数据,因此构造函数解释指定字符集中的 byte[] 数据,因此可以将其解码为 UTF-16。这不是 OP 所要求的。