码迷,mamicode.com
首页 > 其他好文 > 详细

unicode学习笔记(续)

时间:2015-07-02 15:56:42      阅读:123      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!