首页 > 其他 > 详细

unicode学习笔记(续)

时间:2015-07-02 15:56:22      阅读:149      评论:0      收藏:0      [点我收藏+]

为了学习unicode的utf-8和utf-16编码,写了如下程序进行学习。

import java.nio.charset.Charset;


public class MyStudy {
    
    public static String field = "%-20s";
    
    public static void main(String[] args){        
        System.out.format(field, "utf-16 length");
        System.out.format(field, "utf-8 length");
        System.out.format(field, "utf-16");
        System.out.format(field, "utf-8");
        System.out.format(field, "text");
        
        System.out.println();
        
        String[] arr = {"瓴", "龍", "瓴龍", "一", "一二", "一二三", "a", "ab", "abc"};
        
        for (String str: arr){
            System.out.format(field, str.getBytes(Charset.forName("UTF-16")).length);
            System.out.format(field, str.getBytes(Charset.forName("UTF-8")).length);
            
            System.out.format(field, toHex(str.getBytes(Charset.forName("UTF-16"))));
            System.out.format(field, toHex(str.getBytes(Charset.forName("UTF-8"))));
            
            System.out.format(field, str);
            
            System.out.println();
        }
    }
    
    
    public static String toHex(byte[] b) {
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < b.length; i++) {
            builder.append(String.format("%02x", b[i]));
        }
        
        
        return builder.toString();
    }
    
}

该程序的输入结果是:

技术分享



unicode学习笔记(续)

原文:http://my.oschina.net/u/2291753/blog/473489

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!