二级JAVA:实现整句汉字拆分、转换为ASCII
来源:优易学  2011-9-18 15:31:15   【优易学:中国教育考试门户网】   资料下载   IT书店

  大家都知道,一个汉字等于两个byte的大小。二进制数据通过网络传输时,如果两个byte都超过128则会合并成一个Unicode(汉字)字符,本文的代码主要实现的功能是:把这些汉字拆分为byte,然后重新变为ASCII类型的字符串。
  1. public static String ChineseToASCII(byte[] rec) { //从字节读取内容
  2.      ByteArrayInputStream bais = new ByteArrayInputStream(rec);
  3.      DataInputStream dis = new DataInputStream(bais);
  4.      String BTS=null;
  5.      try {
  6.      BTS=new String(rec,"ISO8859-1");//转换编码
  7.      bais.close();
  8.      dis.close();
  9.      } catch (Exception e) {
  10.      e.printStackTrace();
  11.      }
  12.      return  BTS;
  13.  }
  14.
  15.     /**
  16.      * @param args the command line arguments
  17.      */
  18.     public static void main(String[] args) {
  19.         String source="一二三四五六七八九十";
  20.         System.out.println(source.length());
  21.
  22.         String target=ChineseToASCII(source.getBytes());
  23.         System.out.println(target);
  24.         System.out.println(target.length());
  25.
  26.     }
  结果是:
  compile:
  run:
  10
  ???????????ù??°????? ASCII字符如果超过128,则会显示为?,但是其本身的值不变
  20
  BUILD SUCCESSFUL (total time: 1 second)

责任编辑:小草

文章搜索:
 相关文章
热点资讯
资讯快报
热门课程培训