黑马程序员技术交流社区

标题: 分享一下我的按字节截取String的取巧函数 [打印本页]

作者: mingtianrsm    时间: 2014-10-1 16:50
标题: 分享一下我的按字节截取String的取巧函数
/**
         * 定义mySubString方法,用来对字符串经行切割。
         * @param str       形参,用来传递需要进行切割的字符串
         * @param count     形参,用来传递需要经行切割的位数
         * @throws UnsupportedEncodingException
         */
        public static StringBuffer mySubString(String str, int count) throws UnsupportedEncodingException {
                if(str.length() == 0) {                                 //对传入的字符串进行判断,如果传入的字符串为空,则直接返回空值
                        System.out.println("您传入的字符串为null!");
                        return null;
                }
                byte[] charBytes = str.getBytes("GBK");                 //获取字符串每一位字符在GBK码表中对应数值的数组
                if(count <= 0 || count >= charBytes.length) {           //对传入的截取位数进行判断,如果传入的count值等于0或者比字符串位数大,则直接返回空值
                        System.out.println("您要截取的位数不正确,请重新设置截取位数!");
                        return null;
                }
                StringBuffer subdStr = new StringBuffer();              //定义一个StringBuffer,用来存放截取得到的字符串
                for(int i = 0; i < count; i ++) {
                        if(charBytes[i] > 0) {                              //对字符进行判断,大于0的字符为英文字符,可以直接用charAt(index)获得
                                subdStr.append(str.charAt(i));
                        }else {
                                if(count-i > 1) {                               //如果是中文字符,则对剩余的截取位数经行判断,如果大于1,则用charAt(index)获得该位置的字符,并将角标i加1,;否则,直接结束循环
                                        subdStr.append(str.charAt(i));
                                        i ++;
                                }else {
                                        break;
                                }
                        }
                }
                return subdStr;
        }




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2