Java之字符串的编码方式

前言

UTF-8是Unicode的一种实现方式,也就是它的字节结构有特殊要求,所以我们说一个汉字的范围是0X4E00到0x9FA5,是指unicode值,至于放在utf-8的编码里去就是由三个字节来组织,所以可以看出unicode是给出一个字符的范围,定义了这个字是码值是多少,至于具体的实现方式可以有多种多样来实现。

idea中默认的字符串编码方式为utf-8

System.out.println(System.getProperty("file.encoding"));

在这里插入图片描述
更改编码方式:settings->fileCoding->GlobalEncoding = GBK
输出结果:

在这里插入图片描述

utf-8和GBK中字符串所占用的字节数

    public static void print(String s) {
        for (byte aByte : s.getBytes()) {
            System.out.println(aByte);
        }
        System.out.println("----------------");
    }

GBK编码方式下,键盘在中文状态

数字字母占一个字节,符号或者中文占用两个字节

    public static void main(String[] args) {
        String s1 = "2";
        print(s1);
        String s2 = ";";
        print(s2);
        String s3 = "方";
        print(s3);
        String s4 = "23f方";
        print(s4);
    }

在这里插入图片描述

gbk编码方式下,键盘在英文状态

字母数字占,符号用1个字节,中文占用两个字节

    public static void main(String[] args) {
        String s1 = "2";
        print(s1);
        String s2 = ";";
        print(s2);
        String s3 = "f";
        print(s3);
        String s4 = "23f方";
        print(s4);
    }

在这里插入图片描述

utf-8的方式下

中文,中文符号占用3个字节,英文符号占用1个字节,字母数字占用1个字节

    public static void main(String[] args) {
        String s1 = "2";
        print(s1);
        String s2 = ";";
        print(s2);
        String s3 = "方";
        print(s3);
        String s4 = "23f方";
        print(s4);
    }

在这里插入图片描述

总结

utf-8下中文中文符号占用3字节,英文符号,字母数字占用1个字节

gbk下中文中文符号占用2字节,英文符号,字母数字占用1个字节

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值