Java汉字处理

来源:互联网 发布:淘宝丝芙兰68折代购 编辑:程序博客网 时间:2024/06/03 14:47

1、字符串长度

 

   String s1 = "我是中国人";
   String s2 = "imchinese";
   String s3 = "im中国人";
   System.out.println(s1+":"+new String(s1).length());
   System.out.println(s2+":"+new String(s2).length());
   System.out.println(s3+":"+new String(s3).length());

 

   输出结果:
   我是中国人:5
   imchinese:9
   im中国人:5

 

   结论:字符串里如果有双字节的字符java就把每个字符都按双字节编码,如果都是单字节的字符就按单字节编码。

 

2、提取字符串中的汉字

 

   String str = "af我是kz中h国m人ig";
   char ch[] = str.toCharArray();
   for (int i = 0; i < ch.length; i++) {
     if (ch[i] > 255) {
       System.out.print(ch[i]);
    }
  }

 

  输出结果:

  我是中国人

 

3、打印汉字编码

(1)打印汉字的unicode编码

 

   char ch = '中';
   System.out.println(Integer.toHexString(ch));

 

   输出结果:

   4e2d

 

(2)打印汉字的GBK编码

 

   String str = "中";
   byte[] bt = str.getBytes("GBK");
   System.out.println(Integer.toHexString(bt[0]).substring(6)
     +Integer.toHexString(bt[1]).substring(6));

 

   输出结果:

   d6d0

 

   说明:java内部使用的是unicode编码,汉字的Unicode编码范围为/u4E00-/u9FA5 或/uF900-/uFA2D,如果不在这个范围内就不是汉字。我们用char定义一个变量,如char ch='中'; 这时,ch是Unicode编码的。GBK编码与unicode编码是不同的两种编码方式,因此它们打印出的值是不一样的。GBK的整体编码范围是为0x8140-0xFEFE,不包括低字节是0x7F的组合。高字节范围是0x81-0xFE,低字节范围是0x40-7E和0x80-0xFE。

 

4、用两个byte组成一个汉字

 

   byte bb[] = new byte[2];
   bb[0] = -42;
   bb[1] = -48;
   String str = new String(bb);
   System.out.println(str);

 

  输出结果:

  中

 

原创粉丝点击