分享

JAVA 按字节截取字符串

 跃来跃去 2009-12-15
    /**
     * 字符串按字节截取
     * @param str 原字符
     * @param len 截取长度
     * @param elide 省略符等追加到截取完的后边
     * @return String
     */
    public static String splitString(String str,int len,String elide) {
        if(str == null) {
            return "";
        }
        byte[] strByte = str.getBytes();
        int strLen = strByte.length;
        int elideLen = (elide.trim().length() == 0) ? 0 : elide.getBytes().length;
        if (len >= strLen || len < 1) {
            return str;
        }
        if (len - elideLen > 0) {
            len = len - elideLen;
        }
        int count = 0;
        for (int i = 0; i < len; i++) {
            int value = (int) strByte[i];
            if (value < 0) {
                count++;
            }
        }
        if (count%2 != 0) {
            len = (len == 1)?len+1:len - 1;
        }
        return new String(strByte, 0, len) + elide.trim();
    }     

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约