Java字符串找出4个字节长度的字符

不解释,直接上代码: 
由于Iteye代码贴四个字节的UTF-8字符出错,特能图的方式发布几个特殊字符: 



Java代码  收藏代码
  1. public class Byte4Check {  
  2.   
  3.     public static void main(String args[]) throws UnsupportedEncodingException {  
  4.         String nickName = "12葫";  
  5.   
  6.         byte[] t = nickName.substring(01).getBytes("UTF-8");  
  7.         for (byte tt : t) {  
  8.             System.out.println(tt);  
  9.         }  
  10.         System.out.println("====================");  
  11.         byte[] t1 = nickName.getBytes("UTF-8");  
  12.         for (int i = 0; i < t1.length;) {  
  13.             byte tt = t1[i];  
  14.             if (CharUtils.isAscii((char) tt)) {  
  15.                 byte[] ba = new byte[1];  
  16.                 ba[0] = tt;  
  17.                 i++;  
  18.                 String result = new String(ba);  
  19.                 System.out.println("1个字节的字符");  
  20.                 System.out.println("字符为:" + result);  
  21.             }  
  22.             if ((tt & 0xE0) == 0xC0) {  
  23.                 byte[] ba = new byte[2];  
  24.                 ba[0] = tt;  
  25.                 ba[1] = t1[i+1];  
  26.                 i++;  
  27.                 i++;  
  28.                 String result = new String(ba);  
  29.                 System.out.println("2个字节的字符");  
  30.                 System.out.println("字符为:" + result);  
  31.             }  
  32.             if ((tt & 0xF0) == 0xE0) {  
  33.                 byte[] ba = new byte[3];  
  34.                 ba[0] = tt;  
  35.                 ba[1] = t1[i+1];  
  36.                 ba[2] = t1[i+2];  
  37.                 i++;  
  38.                 i++;  
  39.                 i++;  
  40.                 String result = new String(ba);  
  41.                 System.out.println("3个字节的字符");  
  42.                 System.out.println("字符为:" + result);  
  43.             }  
  44.             if ((tt & 0xF8) == 0xF0) {  
  45.                 byte[] ba = new byte[4];  
  46.                 ba[0] = tt;  
  47.                 ba[1] = t1[i+1];  
  48.                 ba[2] = t1[i+2];  
  49.                 ba[3] = t1[i+3];  
  50.                 i++;  
  51.                 i++;  
  52.                 i++;  
  53.                 i++;  
  54.                 String result = new String(ba);  
  55.                 System.out.println("4个字节的字符");  
  56.                 System.out.println("字符为:" + result);  
  57.             }  
  58.         }  
  59.     }  
  60. }  



参考文献: 
http://www.yunmx.com/archives/2011/138.htm 
http://zh.wikipedia.org/wiki/UTF-8

posted @ 2015-09-11 16:39  雄狮_杜  阅读(1575)  评论(0编辑  收藏  举报