如何在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.
答案 0 :(得分:1)
String
个对象在内部保存UTF-16数据。如果你想要的是将String
编码为UTF-8进行导出,则需要将其转换为UTF-8编码的byte[]
数组,例如使用String.getBytes(Charset charset)
或{{ 3}}方法,例如:
byte[] byteArray = text.getBytes(StandardCharsets.UTF_8);
byte[] byteArray = text.getBytes("UTF-8");
答案 1 :(得分:-1)
您可以将String构造函数与charset参数一起使用:
try
{
final String s = new String("AnyStringThatYouwant to convert", "UTF-8");
}
catch (UnsupportedEncodingException e)
{
Log.e("utf8", "conversion", e);
}