java(16)--中英文混合,截取一定长度,保持不乱码

来源:互联网 发布:安卓微信加好友软件 编辑:程序博客网 时间:2024/06/18 15:30

因为中文是两个字节,如果需要截取一定字符长度,比如短信字数,所以需要保证其不乱码

import java.io.UnsupportedEncodingException;public class Demo {    /**     * gb2312  gbk 区别     * gb2312 码表 兼容了一个 ascii码表 ascii字符占一个字节(正数)  中文占两个字节(两个负数)     * 升级gbk码表  和上面一样, 不同在于: 中文 第一个字节是负数 第二个可正可负     * @throws UnsupportedEncodingException      */    public static void main(String[] args) throws UnsupportedEncodingException {String str = "abc中国人";        byte[] buf = str.getBytes("gbk");   // ctrl+2,L        // 截取数组的一部分,要求保留完整的中文        //decode(buf,8);        decodeByGBK(buf, 6);    }    private static void decodeByGBK(byte[] buf, int len) {        // gbk 编码        boolean b = false;      // b true        for(int i=0; i<len; i++) {            if(b)                b = false;            else if(buf[i]<0)                b = true;        }        if(b)            len--;        String str = new String(buf, 0, len);        System.out.println(str);    }    private static void decode(byte[] buf, int len) {        // 统计负数的个数        int count = 0;        for(int i=0; i<len; i++) {            if(buf[i]<0)                count++;        }        if(count%2==1)            len--;        String str = new String(buf, 0, len);        System.out.println(str);    }}
0 0
原创粉丝点击