码迷,mamicode.com
首页 > 编程语言 > 详细

算法之截取带汉字的字符串

时间:2017-07-02 20:25:10      阅读:127      评论:0      收藏:0      [点我收藏+]

标签:row   hal   throw   bsp   输入   bytes   als   []   str   

输入“我ABC汉DEF”和字节数6,应该输出“我ABC”,而不是“我ABC+汉的半个”。

public class CutOutHanzi {
    public static void main(String[] args) throws UnsupportedEncodingException {
        String str = "我ABC汉DEF";
        cutOutGBK(str,6);
    }
    public static String cutOutGBK(String str,int n) throws UnsupportedEncodingException{//n为要截取的字节数
        byte[] buf = str.getBytes("GBK");
        int num = 0;
        boolean isHanziFirstHalf = false;
        for (int i = 0; i < n; i++) {
            if(buf[i]<0 && !isHanziFirstHalf)
                isHanziFirstHalf = true;
            else{
                num++;
                isHanziFirstHalf = false;
            }
        }
        return str.substring(0,num);
    }
}

 

算法之截取带汉字的字符串

标签:row   hal   throw   bsp   输入   bytes   als   []   str   

原文地址:http://www.cnblogs.com/lxcmyf/p/7106919.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!