【问题标题】:How Can I change a string to the UTF-8 format in android如何在android中将字符串更改为UTF-8格式
【发布时间】: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 encoding utf-8


    【解决方案1】:

    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");
    

    【讨论】:

      【解决方案2】:

      您好,您可以使用带有 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 所要求的。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-26
      • 1970-01-01
      • 2011-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多