292 字符串中的编码解码问题

36 篇文章 0 订阅

292 字符串中的编码解码问题

> 我们采用IDEA平台编写代码

编码

byte[] getBytes();

使用平台的默认字符集,将该String编码为一系列字节,将结果存储到新的 字节数组

byte[] getBytes(String charsetName);

使用指定的字符集,将该String编码为一系列字节,将结果存储到 新的字节数组

解码

String(byte[] bytes);

使用平台默认的字符集,解码指定的字符数组,构造新的String

String(byte[] bytes,String charsetName);

使用指定的字符集,解码指定的字符数组,构造新的String

【代码思路】

试用以上4个方法

【小结】

//用指定字符集编码

        String s = "中国";

        byte[] b = s.getBytes("UTF-8");

        System.out.println(Arrays.toString(b));

--------------------------------------------------------------

1 package e292; 2

3 import java.io.UnsupportedEncodingException;

4 import java.nio.charset.StandardCharsets;

5 import java.util.Arrays;6

7 public class StringDemo {

8     public static void main(String[] args) throws UnsupportedEncodingException {

9 //用默认字符集编码

10         String s11 = "中国";

11         byte[] b11 = s11.getBytes();

12         System.out.println("12\t" + Arrays.toString(b11));//[-28, -72, -83, -27, -101, -67]

13

14 //用指定字符集编码

15         String s12 = "中国";

16         byte[] b12 = s12.getBytes("UTF-8");

17         System.out.println("17\t" + Arrays.toString(b12));

18

19         String s13 = "中国";

20         byte[] b13 = s13.getBytes("GBK");

21         System.out.println("21\t" + Arrays.toString(b13));

22

23 // 解码,用默认字符集

24         String s21 = "中国";

25         byte[] b21 = s21.getBytes();

26         String ss21 = new String(b21);

27         System.out.println("27\t" + ss21);

28

29 // 解码,用指定字符集

30         String s22 = "中国";

31         byte[] b22 = s22.getBytes();

32         String ss22 = new String(b22, "UTF-8");

33         System.out.println("33\t" + ss22);

34

35         String s23 = "中国";

36         byte[] b23 = s23.getBytes();

37         String ss23 = new String(b23, "GBK");

38         System.out.println("38\t" + ss23);

39     }

40 }

41 /*

42 12 [-28, -72, -83, -27, -101, -67]

43 17 [-28, -72, -83, -27, -101, -67]

44 21 [-42, -48, -71, -6]

45 27 中国

46 33 中国

47 38 涓浗

48  */

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值