java按字節截取字符串


public class SubByteString {

    private static String subStringByByte(String str, int len) {
        String result = null;
        if (str != null) {
            byte[] a = str.getBytes();
            if (a.length <= len) {
                result = str;
            } else if (len > 0) {
                result = new String(a, 0, len);
                int length = result.length();
                if (str.charAt(length - 1) != result.charAt(length - 1)) {
                    if (length < 2) {
                        result = null;
                    } else {
                        result = result.substring(0, length - 1);
                    }
                }
            }
        }
        return result;
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        String str1="一百二十個字符怎么就那么難弄呢我該說些啥呢算了還是先扯扯把哎還不到120個字啊讓我怎么測試asdfghjklqwe哈rtuo";
        byte[] a = str1.getBytes();
        String str2 = subStringByByte(str1,100);
        System.out.println("--str1.length="+str1.length()+"----Byte長度="+a.length+"-------str2="+str2+"------");

    }

}

解析:上面這個方法將漢字默認為2個字節,其他為1個字節,缺點是遇到UTF-8等編碼格式的時候不能用,經過代碼驗證"UTF-8"是默認一個漢字占3個字節。

結果:--str1.length=62----Byte長度=105-------str2=一百二十個字符怎么就那么難弄呢我該說些啥呢算了還是先扯扯把哎還不到120個字啊讓我怎么測試asdfghjklqwe------

 

public static String getSubString(String targetString, int byteIndex)
            throws Exception {
        if (targetString.getBytes("UTF-8").length < byteIndex) {
            throw new Exception("超過長度");
        }
        String temp = targetString;
        for (int i = 0; i < targetString.length(); i++) {
            if (temp.getBytes("UTF-8").length <= byteIndex) {
                break;
            }
            temp = temp.substring(0, temp.length() - 1);
        }
        return temp;
    }

解析:可根據想要的編碼方式進行截取字符串,UTF-8編碼下漢字占3個字節。可以根據需要改為gbk方式等等,很方便的。推薦!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM