老問題,給定字符串按字節長度截取子串

灬猜想灬 14年前發布 | 2K 次閱讀 AutoCAD SSD Hyperic HQ 推薦引擎

public class CutString
{
    public static void main(String[] args) throws Throwable
    {
        //begin 起始字節位置(索引值), length 截取字節長度
        int begin = 1, length = 10;
        String s = "?a①㈡⑶⒋Ⅴⅵdf龘s哦的a【《df才朤??╋";
        byte[] bt = s.getBytes("GBK");

    //判斷起始位置的字節歸屬
    //如果起始字節不是字符首字節,則起始位置前移一位
    if (bt[begin] < 0)
    {
        int count = 0;
        for (int i = 0; i <= begin; ++i)
        {
            if (bt[i] < 0)
            {
                count++;
            }
        }
        if (count % 2 == 0)
        {
            //位置前移
            begin--;
        }
    }

    String result = new String(bt,begin,length,"GBK");
    //System.out.println(result);
    char last = result.charAt(result.length()-1);

    //如果最后一位是占雙字節的字符
    //截取它的一半就會出現"?",對應Unicode碼為0xFFFD
    if (last == 0xFFFD)
    {
        result = result.substring(0,result.length()-1);
    }
    System.out.println(result);
}

}</pre>

 本文由用戶 灬猜想灬 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!