老问题,给定字符串按字节长度截取子串

14年前
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);   }  }