java按字节截取字符串

您所在的位置:网站首页 java中文字符字节截取 java按字节截取字符串

java按字节截取字符串

2024-07-08 07:18| 来源: 网络整理| 查看: 265

首先分编码格式,gbk和gb2312公用一套方案,,而u8是另一套。

为什么呢,因为gbk和gb2312是两个字节表示一个汉字,前者两个字节的值都是负数,后者第二个数有时为正,比如(琲bei)

那u8呢,是三个字节表示一个汉字,所以判断条件比gbk多了一点。

String类的length()方法是以unicode代码单元,换言之就是char的个数为来统计的。所以使用subString等截取出来的子串都不会出现半个汉字的情况,因为java一个char类型可以存放一个汉字(2个字节)。而如果以字节byte来截取字符串,就会出现半个汉字的情况。

 

 

不多说,看程序-----

package 按字节截取字符串; import java.io.IOException; /** * 以u8编码讲解按字节截取字符串 * * @author nice * */ public class DemoUtf { public static void main(String[] args) throws IOException { // 定义一个字符串 String str = "asd我是高手wuha高手hhh"; // 求字符串得长度 int len = str.getBytes("utf-8").length; // 循环打印所有在字符串长度范围内的取值输出结果 for (int i = 0; i < len; i++) { System.out.println("按" + (i + 1) + "字节截取:" + currentString(str, i + 1)); } } private static String currentString(String str, int len) throws IOException { // 先把字符串转换为字符数组 byte[] b = str.getBytes("utf-8"); // 定义一个计数器 int count = 0; // 从最后一个字节开始做判断 for (int i = len - 1; i >= 0; i--) { if (b[i] < 0) count++; else break; } // 在for循环里面判断完后,根据u8编码三个字节组成一个汉字的特点,可以推出指定字节对应是不是一个完整的汉字, // 不是就返回到字符串长度减去这个不完整的字节数 // 是3的倍数,那就是一个完整的汉字 if (count % 3 == 0) return new String(b, 0, len, "utf-8"); // 是汉字前面的哪个字节,就减去一个个字节 else if (count % 3 == 1) return new String(b, 0, len - 1, "utf-8"); // 是汉字中间的哪个字节,就减去两个字节 else return new String(b, 0, len - 2, "utf-8"); } } package 按字节截取字符串; import java.io.IOException; /** * 以gbk编码讲解。gb2312可能略有不同,前者是两个负数,后者第二个有时是正数,比如这个琲(bei) u8的话,他是用三个字节表示的。 * 比较法和gbk类似(取余判断多了一些) * * @author nice * */ public class Demo { public static void main(String[] args) throws IOException { String str = "ab琲琲cd琲琲"; // String str = "ab你好cd谢谢"; int len = str.getBytes("GBK").length; for (int i = 0; i < len; i++) { System.out.println("截取" + (i + 1) + "个字节的结果是" + outStringByByte(str, i + 1)); } } private static String outStringByByte(String str, int len) throws IOException { byte[] btf = str.getBytes("gbk"); int count = 0; for (int j = len - 1; j >= 0; j--) { if (btf[j] < 0) count++; else break; } if (count % 2 == 0) return new String(btf, 0, len, "gbk"); else return new String(btf, 0, len - 1, "gbk"); } }

以上,谢谢观看



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3