截取字符串,輸入爲一個字符串或字節數,輸出爲按字節截取的字符串,但要保證漢字不能截取半個

	/**
     * 截取字符串,輸入爲一個字符串或字節數,輸出爲按字節截取的字符串,但要保證漢字不能截取半個
     * 如“我ABC”4,應該截爲“我AB”,輸入“我ABC漢DEF”,6,應該輸出爲“我ABC”而不是“我ABC+漢的半個”。
     */
    public String splitString(String str, int length) {
        String resultStr = null;
        byte[] strBytes = str.getBytes();
        int byteLength = strBytes.length;

        if (length > byteLength) {
            length = byteLength;
        }

        int splitLen = length;
        while (strBytes[splitLen-1] < 0) {
            --splitLen;
        }

        resultStr = new String(strBytes, 0, splitLen);
        return resultStr;
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章