java 获取字符串unicode编码的三种方式


   
    public static void main(String[] args) throws UnsupportedEncodingException {
        // 获取unicode码的几种方式
        // 第一种
        System.err.println("第一种-----toCodePoints");
        String test = "a汉字";
        int[] asds = StringUtils.toCodePoints(test);
        for (int asd : asds) {
            System.err.println("int整型:"+asd);
            String x = Integer.toHexString(asd);
            if (x.length() <= 2) {
                x = "\\u00" + x;
            } else {
                x = "\\u" + x;
            }
            System.err.println("unicode码" + x);
        }
        //第二种
        System.err.println("第二种-----getBytes");
        byte[] bytes = test.getBytes("unicode");

        List<Object> list = new ArrayList<>();
        for (byte aByte : bytes) {
            System.err.println("byte字节:"+aByte);
            String x = Integer.toHexString(aByte);
            if ((-2 != aByte) && (-1 != aByte)) {
                list.add(x);
            }
        }
        for (int i = 0; i < list.size(); i = i + 2) {
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append(list.get(i));
            stringBuilder.append(list.get(i + 1));
            if (stringBuilder.length() < 4) {
                for (int j = 0; j < 4 - stringBuilder.length(); j++) {
                    stringBuilder.insert(0, "0");
                }
            }
            System.err.println("unicode码" + "\\u".concat(stringBuilder.toString()));
        }
        // 第三种
        System.err.println("第三种-----toCharArray");
        char[] chars = test.toCharArray();
        for (char aChar : chars) {
            System.err.println("char字符:"+aChar);
            String x = Integer.toHexString(aChar);
            if (x.length() <= 2) {
                x = "\\u00" + x;
            } else {
                x = "\\u" + x;
            }
            System.err.println("unicode码" + x);
        }
    }

输出结果

第一种-----toCodePoints
int整型:97
unicode码\u0061
int整型:27721
unicode码\u6c49
int整型:23383
unicode码\u5b57
第二种-----getBytes
byte字节:-2
byte字节:-1
byte字节:0
byte字节:97
byte字节:108
byte字节:73
byte字节:91
byte字节:87
unicode码\u0061
unicode码\u6c49
unicode码\u5b57
第三种-----toCharArray
char字符:a
unicode码\u0061
char字符:汉
unicode码\u6c49
char字符:字
unicode码\u5b57
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

b0b0大魔王

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值