最大字节数取子串

import java.io.UnsupportedEncodingException;

/*
 * 定义一个方法,按照最大的字节数来取子串。
 * 如:对于“ab你好”,如果取三个字节,那么子串就是ab与“你”字的
 * 半个,那么半个就要舍弃。如果取四个字节就是“ab你”
 * ,取五个字节还是“ab你”。
 * 
 */

public class TestCode {
    public static void main(String[] args) throws
    UnsupportedEncodingException {
        String st = "ab你Appl琲e还行吧dhgd琲";
        //以下这个过程为了测试
        byte[] buf = st.getBytes("GBK");
        for(int i = 0; i<buf.length;i++){
            String substr = cutStringBybyte(st,i+1);
            System.out.println("截取"+(i+1)+"个字节后的字符串为"+substr);
        }
    }

    public static String cutStringBybyte(String str,int len) throws 
        UnsupportedEncodingException{
        //按GBK解码
        byte[] buf = str.getBytes("GBK");
        //这步关键,定义一个计数器,用于记录负数个数
        int count = 0;
        /*这种写法效率低,碰到特殊字“琲”第一个字节是负数,
        第二个字节是正数这种情况,不能得到正确结果,可以试试看
        原因这里不解释,可以自己分析*/
//      for(int i = 0;i<len;i++){
//          if(buf[i]<0){
//              count++;
//          }
//      }
        /*这种写法效率要高,且要好
        数据从数组里面倒着列出很棒,解决了“琲”这类特殊汉字的问题
        有兴趣,自己独立思考这个问题
        思想:
        直到遍历到字母为止,看汉字的字节有多少个
        奇数就要舍弃一位,偶数就不必舍弃,规律*/
        for(int i= len-1;i>=0;i--){
            if(buf[i]<0){
                count++;
            }else{
                break;
            }
        }
        //如果为偶数说明汉字字节读完
        if(count%2==0){
            return new String(buf,0,len);
        }else{
            //为奇数说明汉字只读了一个字节,应当舍去那个字节
            return new String(buf,0,len-1);
        }
    }
}
posted @ 2016-11-08 16:32  第五个世界  阅读(97)  评论(0编辑  收藏  举报